import { RestrictionType } from "@iabtechlabtcf/core";

import type { TCModel, Vendor } from "@iabtechlabtcf/core";

function isPurposeEnabledForVendor(
    model: TCModel,
    id: number,
    isLegInt: boolean,
    { id: vendorId, legIntPurposes }: Vendor,
) {
    const publisherRestrictions = model.publisherRestrictions.getRestrictions(vendorId);
    const disabledPurposes = publisherRestrictions
        .map(
            ({ purposeId, restrictionType }) =>
                purposeId === id && restrictionType === RestrictionType.NOT_ALLOWED && purposeId,
        )
        .filter(Boolean);

    if (disabledPurposes.indexOf(id) > -1) {
        return false;
    }

    let legIntRestriction = publisherRestrictions.filter(
        ({ purposeId, restrictionType }) => purposeId === id && restrictionType !== RestrictionType.NOT_ALLOWED,
    )[0]?.restrictionType;

    // Fallback to default setting
    if (!legIntRestriction) {
        legIntRestriction =
            legIntPurposes.indexOf(id) > -1 ? RestrictionType.REQUIRE_LI : RestrictionType.REQUIRE_CONSENT;
    }

    if (isLegInt && legIntRestriction === RestrictionType.REQUIRE_CONSENT) {
        return false;
    } else if (!isLegInt && legIntRestriction === RestrictionType.REQUIRE_LI) {
        return false;
    }

    return true;
}

export { isPurposeEnabledForVendor };
