import type { CookieConsentManagerOptions } from "./manager.js";
import type { ServiceTagManager } from "../types/service.js";

const LABEL_GTM = "Google Tag Manager";
const LABEL_MTM = "Matomo Tag Manager";

const PRESET_ID_TAG_MANAGER_REGEXP = /^(gtm|mtm|(gtm-|mtm-).*)$/;

type ManagerFeatures = {
    events: boolean;
    executeCodeWhenNoTagManagerConsentIsGiven: boolean;
};

function getManagerDependingVariables(
    setCookiesViaManager: ServiceTagManager,
    {
        presetId,
        isGcm,
    }: Pick<CookieConsentManagerOptions, "isGcm"> & {
        presetId: string;
    },
) {
    let useGlobalObjectName: "dataLayer" | "_mtm";
    let getDataLayer: () => any[];
    let serviceIsManager = false;
    let managerLabel = "";
    let expectedManagerPresetId: string;
    const features: ManagerFeatures = {
        events: true,
        executeCodeWhenNoTagManagerConsentIsGiven: true,
    };

    let useManager = setCookiesViaManager || "none";
    if (useManager === "googleTagManagerWithGcm" && !isGcm) {
        useManager = "googleTagManager";
    }

    switch (useManager) {
        case "googleTagManager":
        case "googleTagManagerWithGcm":
            expectedManagerPresetId = "gtm";
            useGlobalObjectName = "dataLayer";
            managerLabel = LABEL_GTM;
            features.events = useManager !== "googleTagManagerWithGcm";
            break;
        case "matomoTagManager":
            expectedManagerPresetId = "mtm";
            useGlobalObjectName = "_mtm";
            managerLabel = LABEL_MTM;
            break;
        default:
            features.events = false;
            features.executeCodeWhenNoTagManagerConsentIsGiven = false;
            break;
    }

    if (useGlobalObjectName) {
        getDataLayer = () => {
            window[useGlobalObjectName] = window[useGlobalObjectName] || [];
            return window[useGlobalObjectName];
        };
    }

    if (PRESET_ID_TAG_MANAGER_REGEXP.test(presetId)) {
        serviceIsManager = true;
        features.events = false;
        features.executeCodeWhenNoTagManagerConsentIsGiven = false;
    }

    return { getDataLayer, useManager, serviceIsManager, managerLabel, expectedManagerPresetId, features };
}

export { LABEL_GTM, LABEL_MTM, PRESET_ID_TAG_MANAGER_REGEXP, getManagerDependingVariables };
