import { findUsedVendorsForDeclaration } from "./findUsedVendorsForDeclaration.js";

import type { TcfDeclarationFilter } from "../types/tcf.js";
import type { DataCategory, Declarations, Feature, GVL, Purpose, TCModel } from "@iabtechlabtcf/core";

/**
 * Get a list of used declarations for e.g. `purposes`. It can also return an
 * empty array if the given declaration does not have any items/vendors.
 */
function findUsedDeclarations(
    declaration: keyof Omit<Declarations, "stacks">,
    gvl: GVL,
    model: TCModel,
    filterBy: TcfDeclarationFilter,
    sorted = false,
) {
    const { [declaration]: declarations } = gvl;

    const declarationValues = Object.values(declarations) as Array<Feature | Purpose | DataCategory>;

    // Collect a map of `id` => `length of vendors` so we can hide the complete declaration if no vendor is available
    const lengthMap = declarationValues.reduce((map, { id }) => {
        map[id] = findUsedVendorsForDeclaration(gvl, model, id, declaration, filterBy === "legInt", sorted).length;
        return map;
    }, {}) as Record<number, number>;

    return declarationValues.filter(({ id }) => lengthMap[id]);
}

export { findUsedDeclarations };
