import { isDoNotTrack } from "../utils/isDoNotTrack.js";

import type { PreDecisionGateway } from "./gateway.js";

/**
 * When the user has "Do not track" enabled and is allowed to use, let's automatically
 * save the dialog without any action.
 */
const preDecisionGatewayIsDoNotTrack: (active?: boolean) => PreDecisionGateway =
    (active = true) =>
    async ({ getUserDecision, groups }) => {
        const essentialGroupObj = groups.find(({ isEssential }) => isEssential);

        if (getUserDecision() !== false || !active) {
            return false;
        }

        // As soon we have a legitimate interest, we need to show the cookie banner
        for (const group of groups) {
            if (group !== essentialGroupObj) {
                for (const { legalBasis } of group.items) {
                    if (legalBasis === "legitimate-interest") {
                        return false;
                    }
                }
            }
        }

        return isDoNotTrack() ? "dnt" : false;
    };

export { preDecisionGatewayIsDoNotTrack };
