import type { TcfGvlAdditionalInformation, TcfGvlDeviceStorageDisclosure } from "@devowl-wp/cookie-consent-web-client";

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

type LazyDataForSecondView = {
    tcf?: {
        vendors: Record<
            number,
            {
                additionalInformation?: TcfGvlAdditionalInformation;
                deviceStorageDisclosure?: TcfGvlDeviceStorageDisclosure;
                deviceStorageDisclosureUrl?: string;
                urls: Vendor["urls"];
            }
        >;
    };
};

declare global {
    interface Window {
        rcbLazyPromise?: [Promise<LazyDataForSecondView>, () => void];
    }
}

/**
 * This hook is used to fetch the data for the second view (see also `Frontend#prepareLazyLoad`).
 * It also ensures that this hook can be used on multiple instances (e.g. Cookie Banner and Content Blocker)
 * by not fetching the data multiple times.
 */
function getLazyDataForSecondView(fetcher: () => Promise<LazyDataForSecondView>, hasLazyData?: boolean) {
    const lazyPromise = window.rcbLazyPromise;

    let resolver: () => void;
    let promise: (typeof window.rcbLazyPromise)[0];
    if (!lazyPromise) {
        let resolved = false;

        if (hasLazyData === false) {
            promise = Promise.resolve({});
        } else {
            promise = new Promise<LazyDataForSecondView>((resolve) => {
                resolver = async () => {
                    if (resolved) {
                        return;
                    }
                    resolved = true;
                    resolve(await fetcher());
                };
            });
        }
    } else {
        [promise, resolver] = lazyPromise;
    }

    return [promise, resolver] as const;
}

export { type LazyDataForSecondView, getLazyDataForSecondView };
