import { globalEvents, globalEventTypes } from "@/constants/events";
import { storeActions } from "@/constants/store-actions";
import eventBus from "@/helpers/event-bus/event-bus";
import baseMixin from "@/mixins/base-mixin";
import router from "@/router";
import { routeData, FUNNEL_START_PAGE } from "@/router/constants/routes";
import store from "@/store";
import { handleHardError } from "@/router/methods/error";

export async function errorBeforeEnter(to, from) {
    // Check if `hasAlreadyTriggeredErrror` is available.
    // If we cannot check it (store, getters, or applicationUser is null-ish),
    //   act as if the flag is set, as we are in unstable state.
    if (!store?.getters?.applicationUser) {
        const errorPayload = {
            cause: "Cannot access store during error process.",
            currentPage: from?.name,
            nextPage: to?.name,
        };

        await handleHardError(errorPayload);
        return;
    }

    // If we've already encountered one error, clear session to avoid more.
    // Otherwise mark that we encountered an error here.
    if (store.getters.applicationUser.hasAlreadyTriggeredError) {
        const errorPayload = {
            cause: "Successive errors triggered.",
            currentPage: from?.name,
            nextPage: to?.name,
        };

        await handleHardError(errorPayload);
        return;
    } else {
        await store.dispatch(storeActions.UPDATE_HAS_TRIGGERED_ERROR, true);
    }

    // Add error event to bus
    eventBus.addEventToBus(
        globalEvents.Categories.GLOBAL_ALERT,
        globalEvents.SubCategories.UNKNOWN_ERROR,
        {
            isDismissable: true,
            messageCopy: "",
            messageHeadline: "We're sorry, something went wrong.",
            type: globalEventTypes.Danger,
        }
    );

    let nextPage = FUNNEL_START_PAGE.name;

    baseMixin.methods?.ResetExternalParamsAndHideModal();

    if (store.getters.payment?.insuranceCoverage?.isVerified) {
        nextPage = routeData.VEHICLE_DAMAGE.name;
    }

    if (from.name === nextPage) {
        // Router won't load the page if we redirect to the already existing page
        // Force refresh in this scenario.
        router.go(0);
        return false;
    }

    return {
        name: nextPage,
        replace: false,
    };
}
