import type { CommonContextProps } from "@devowl-wp/react-cookie-banner";
import { yieldMainThread } from "@devowl-wp/react-utils";

import { getCookieConsentManager } from "./getCookieConsentManager.js";

/**
 * Save consent to the backend and apply cookies on running session.
 */
const persistConsent: CommonContextProps["onPersistConsent"] = async ({
    consent,
    gcmConsent,
    markAsDoNotTrack = false,
    buttonClicked,
    blocker = 0,
    blockerThumbnail,
    tcfString,
    recorderJsonString,
    uiView,
}) => {
    const { clientWidth, clientHeight } = document.documentElement;

    let awaitedTcfString: string;
    if (tcfString) {
        awaitedTcfString = tcfString();
        await yieldMainThread();
    }

    await getCookieConsentManager().persistConsent({
        decision: consent,
        gcmConsent,
        markAsDoNotTrack,
        buttonClicked,
        viewPortWidth: clientWidth,
        viewPortHeight: clientHeight,
        blocker,
        blockerThumbnail,
        tcfString: awaitedTcfString,
        recorderJsonString,
        uiView,
    });
};

export { persistConsent };
