import type { DecisionConsentGroups } from "./getUserDecision.js";
import type { ServiceGroup } from "../types/service.js";

/**
 * Get the default decision and respect essential group and legitimate interests.
 */
function getDefaultDecision(groups: ServiceGroup[], respectLegitimateInterests = true): DecisionConsentGroups {
    const essentialGroupObj = groups.find(({ isEssential }) => isEssential);

    // We need always use the current essential group
    const result: DecisionConsentGroups = {
        [essentialGroupObj.id]: essentialGroupObj.items.map(({ id }) => id),
    };

    if (respectLegitimateInterests) {
        for (const group of groups) {
            if (group === essentialGroupObj) {
                continue;
            }

            const ids = group.items
                .filter(({ legalBasis }) => legalBasis === "legitimate-interest")
                .map(({ id }) => id);

            if (ids.length) {
                result[group.id] = ids;
            }
        }
    }

    return result;
}

export { getDefaultDecision };
