import Cookie from "js-cookie";

import { EServiceTemplateGoogleConsentModeTypes } from "@devowl-wp/api-real-cookie-banner";

import type { CookieConsentManagerOptions } from "../apply/manager.js";
import type { ClickableButtonsNamed } from "../types/types.js";

/**
 * Get current user decision for Google Consent Mode from the cookie value.
 */
function getUserGcmDecision(
    cookieName: CookieConsentManagerOptions["gcmCookieName"],
    /**
     * Depending on an implicit consent we need to fill the decision (e.g. when implicitely all services are
     * accepted, we also need to accept all GCM consent types)
     */
    buttonClicked?: ClickableButtonsNamed,
): EServiceTemplateGoogleConsentModeTypes[] {
    // Got it saved locally?
    const localConsent = localStorage.getItem(cookieName);
    if (localConsent) {
        return JSON.parse(localConsent) as EServiceTemplateGoogleConsentModeTypes[];
    }

    const cookieValue = Cookie.get(cookieName);
    return buttonClicked?.startsWith("implicit")
        ? buttonClicked === "implicit_all"
            ? Object.values(EServiceTemplateGoogleConsentModeTypes)
            : []
        : JSON.parse(cookieValue || "[]");
}

export { getUserGcmDecision };
