import { cookieNames } from "@/constants/cookie-names";
import store from "@/store";
import { applicationConfig } from "@/constants/application-config";

/*
    Will update the cookie if present, or create a new one if not.
*/
export function updateOrCreateFunnelCookie() {
    const wasClaimRegistrationDelayed = getFunnelCookie()?.HasDelayedClaimRegistration;
    const shouldSuppressConceptFunnel = getFunnelCookie()?.SuppressConceptFunnel;

    // Set up cookie with all the props.
    setFunnelCookieProperties({
        LastTouched: new Date().toUTCString(),
        SavedSessionTimeoutDate: store.getters.applicationUser.savedSessionTimeout,
        DidHeritageFunnelUpdateLast: false,
        ShouldResetState: false,
        ReferralNumber: store.getters.order.referralNumber,
        ReferralDate: store.getters.order.referralDate,
        ReferralCorrelationId: store.getters.order.referralCorrelationId,
        ReferralParentAccountNumber: store.getters.order.accountNumber,
        HasDelayedClaimRegistration: wasClaimRegistrationDelayed,
        SuppressConceptFunnel: shouldSuppressConceptFunnel,
        SavedSessionId: store.getters.applicationUser.savedSessionId,
    });
}

/*
    Gets the current instance of the funnel cookie.
    Returns null if cookie isn't valid JSON.
*/
export function getFunnelCookie() {
    const cookieJson = document.cookie
        ?.split("; ")
        ?.find((row) => row.startsWith(`${cookieNames.FUNNEL_SESSION_INFO}=`))
        ?.split("=")[1];

    try {
        return JSON.parse(cookieJson);
    } catch (error) {
        return null;
    }
}

/*
    Removes cookie from browser.
*/
export function deleteFunnelCookie() {
    createOrUpdateCookie(cookieNames.FUNNEL_SESSION_INFO, undefined, { maxAge: 0 });
}

/*
    Gets cookie domain value. Localhost will be empty "".
*/
export function getCookieDomainValue() {
    return isLocalhost() ? "" : `domain=${getDomainWithoutSubdomain()};`;
}

/*
    Gets value of dxdev cookie, and then extracts "did" value from it.
    Returns empty string if cookie not found or "did" string not present.
*/
export function getDeviceIdValue() {
    // Sometimes these cookie contains more than the device ID.
    const cookieValue = getCookieValueByName(cookieNames.DXDEV);
    const cookieValuesSplit = cookieValue.split("=");

    // If this is the only value, just use that.
    if (cookieValuesSplit.length === 2 && cookieValuesSplit[0] === "did") {
        return cookieValuesSplit[1];
    }

    const cookieValueMatch = cookieValue.match("^did=[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}");
    if (cookieValueMatch) {
        return cookieValueMatch[0].split("=")[1];
    }

    return "00000000-0000-0000-0000-000000000000";
}

/*
    Gets value of skey cookie, returns 0 if not found.
*/
export function getSessionKeyValue() {
    const cookieValue = getCookieValueByName(cookieNames.SESSION_KEY);

    if (cookieValue) {
        return cookieValue;
    }

    return 0;
}

/*
    Gets value of skey cookie, returns 0 if not found.
*/
export function getSessionIdValue() {
    const cookieValue = getCookieValueByName(cookieNames.SESSION_ID);

    if (cookieValue) {
        return cookieValue;
    }

    return "00000000-0000-0000-0000-000000000000";
}

/* 
    Updates session ID cookie with new expiration date
*/
export function updateSessionIdCookie() {
    createOrUpdateCookie(cookieNames.SESSION_ID, getSessionIdValue(), { maxAge: 60 * 30 });
}

export function setCookieProperties(
    properties,
    { useDefaultFunnelCookieAttributes = true, maxAge, isSecure }
) {
    if (typeof properties == "object") {
        Object.keys(properties).forEach((key) => {
            createOrUpdateCookie(key, properties[key], {
                useDefaultFunnelCookieAttributes,
                maxAge,
                isSecure,
            });
        });
    }
}

/*
===========================
=   PRIVATE FUNCTIONS     =
===========================
*/

/*
    Used to set properties on the funnel cookie.
    Takes an object with properties to set. Will overwrite existing properties.
*/
function setFunnelCookieProperties(properties) {
    if (typeof properties == "object") {
        let cookie = getFunnelCookie();

        if (cookie !== null) {
            Object.keys(properties).forEach((key) => {
                cookie[key] = properties[key];
            });
        }

        const cookieValueJson = JSON.stringify(cookie ?? {});
        createOrUpdateCookie(cookieNames.FUNNEL_SESSION_INFO, cookieValueJson, {});
    }
}

/*
    Used to create a cookie. 
    `useDefaultFunnelCookieAttributes` will set the path and domain to our defaults
*/
function createOrUpdateCookie(
    key,
    value = "",
    { useDefaultFunnelCookieAttributes = true, maxAge, isSecure = true }
) {
    let cookieToAdd = `${key}=${value}; `;

    if (useDefaultFunnelCookieAttributes) {
        cookieToAdd += `path=${applicationConfig.COOKIE_PATH}; ${getCookieDomainValue()} `;
    }
    if (isSecure && !isLocalhost()) {
        cookieToAdd += `secure; `;
    }
    if (!isNaN(maxAge)) {
        cookieToAdd += `max-age=${maxAge};`;
    }

    document.cookie = cookieToAdd;
}

/*
    Gets current domain without the subdomain for cookie.
*/
function getDomainWithoutSubdomain() {
    let url = location.hostname;
    if (isLocalhost()) {
        return "localhost";
    }

    const urlParts = url.split(".");

    return `.${urlParts
        .slice(0)
        .slice(-(urlParts.length === 4 ? 3 : 2))
        .join(".")}`;
}

/*
    Gets cookie value by name, returns empty string if not found.
*/
function getCookieValueByName(name) {
    const value = "; " + document.cookie;
    const parts = value.split("; " + name + "=");

    if (parts.length === 2) {
        return parts.pop().split(";").shift();
    }
    return "";
}

function isLocalhost() {
    return location.hostname.includes("localhost");
}
