import { saveSession } from "@/helpers/heritage-integration/order-helper";
import { buildManualUrl } from "@/router/methods/helpers/build-manual-url";
import { getDestination } from "@/router/methods/helpers/get-destination";
import { savePageData } from "@/router/methods/helpers/save-page-data";
import router from "@/router";
import store from "@/store";

import { handleSoftError } from "@/router/methods/error";

async function navigate(scenario, currentPageName, withSaving = false, forceTopLevelNav = false) {
    // Check to see if calling page is same as current page.
    // If not, cancel navigation before it begins.
    const callingRoute = currentPageName;
    const actualRoute = router.currentRoute.value.name;

    if (callingRoute !== actualRoute) {
        return false;
    }

    const nextPage = getDestination(currentPageName, scenario);

    if (!nextPage) {
        console.error(
            `Could not navigate from ${currentPageName} via scenario ${scenario}. Ensure routing table is configured correctly.`
        );

        const errorPayload = {
            cause: "invalid page name",
            currentPage: currentPageName,
            nextPage: nextPage?.name,
        };

        await handleSoftError(errorPayload);
        return;
    }

    if (withSaving) {
        if (
            store.getters?.applicationUser?.savedSessionId ||
            store.getters?.order?.customer?.emailAddress
        ) {
            await saveSession({ pageNameToLog: nextPage.name });
        }
    }

    // Some pages require manually setting the next url
    // to work with iframes.
    if (forceTopLevelNav) {
        const newUrl = buildManualUrl(nextPage);
        window.top.location.href = newUrl;
        return;
    }

    // All other pages use router.push
    router.push({
        name: nextPage.name,
        query: nextPage.params ?? {},
    });
}

//// -- Aliases: what's actually called

export async function navigateWithoutSaving(scenario, currentPageName) {
    return await navigate(scenario, currentPageName, false);
}

export async function navigateWithSaving(scenario, currentPageName) {
    return await navigate(scenario, currentPageName, true);
}

export async function navigateWithPageData(scenario, currentPageName, pageData = {}) {
    const nextPage = getDestination(currentPageName, scenario);
    await savePageData(nextPage.name, pageData);

    return await navigate(scenario, currentPageName, true);
}

export async function navigateAndForceTopLevelNavigation(
    scenario,
    currentPageName,
    saving = false
) {
    return await navigate(scenario, currentPageName, saving, true);
}
