import { putHtmlCodeToDom } from "@devowl-wp/headless-content-unblocker";

import { getServiceSelection } from "../decision/getServiceSelection.js";

import type { GetServiceSelectionOptions } from "../decision/getServiceSelection.js";

/**
 * Opt-in and opt-out to a set of services for a given data manager like GTM / MTM.
 */
async function applyOptInOutManager(options: GetServiceSelectionOptions, dataLayer: any, isManagerOptOut: boolean) {
    const waitPromises: Promise<void>[] = [];

    /* onlypro:start */
    const { isManagerActive, iterateServices } = getServiceSelection(options);

    // When there is a manager, let's push all opt-in and opt-out events (parallel)
    if (dataLayer) {
        // Only dispatch the events when Google Tag Manager compatibility is explicitely activated
        // Opt-in events
        iterateServices((group, { tagManagerOptInEventName: event }, isOptIn, { features }) => {
            if (isOptIn && event && features.events) {
                dataLayer.push({
                    event,
                });
            }
        });

        // Wait x seconds and apply opt-out events (should we add this to `waitPromises`?! I do not think so)
        setTimeout(
            () =>
                iterateServices((group, { tagManagerOptOutEventName: event }, isOptIn, { features }) => {
                    if (!isOptIn && event && features.events) {
                        dataLayer.push({
                            event,
                        });
                    }
                }),
            1000,
        );
    } else if (isManagerActive && isManagerOptOut) {
        // The manager got opt out, let's execute scripts that are explicitly only for this case (sequentially)
        await iterateServices(
            async (group, { codeDynamics, codeOptIn, executeCodeOptInWhenNoTagManagerConsentIsGiven }, isOptIn) => {
                if (isOptIn && executeCodeOptInWhenNoTagManagerConsentIsGiven) {
                    waitPromises.push(putHtmlCodeToDom(codeOptIn, codeDynamics));
                }
            },
        );
    }
    /* onlypro:false */

    return { ready: Promise.all(waitPromises) };
}

export { applyOptInOutManager };
