import { storeMutations } from "@/constants/store-mutations";
import { getBoolFromString } from "@/helpers/boolean-helper";
import { getFunnelCookie } from "@/helpers/heritage-integration/cookie-helper";
import { routeData } from "@/router/constants/routes";
import { isVerifiedInsurance } from "@/router/methods/helpers/requires-verified-redirect";
import store from "@/store";
import { queryStrings } from "@/constants/query-strings";
import baseMixin from "@/mixins/base-mixin";
import { storeActions } from "@/constants/store-actions";
import { consumeQueryFromStash } from "@/router/methods/helpers/querystring-stash";

export async function vehicleBeforeEnter(to, from) {
    // If cookie indicates that vehicle has changed during insurance flow, reset parts info.
    const hasVehicleChanged = getBoolFromString(getFunnelCookie()?.HasDelayedClaimRegistration);
    if (hasVehicleChanged) {
        store.commit(storeMutations.RESET_GLASS_PARTS_STATE);
    }

    // If there is a zip querystring, consume & commit it here.
    const newZipFromQuerystring = consumeQueryFromStash(queryStrings.ZIP_CODE);
    if (newZipFromQuerystring) {
        const zipData = await baseMixin.methods.getZipCodeData(
            newZipFromQuerystring,
            routeData.VEHICLE.name
        );

        if (zipData.isValid) {
            store.dispatch(storeActions.SAVE_SERVICE_ZIP_CODE_INFO, {
                zipCode: newZipFromQuerystring,
                state: zipData.state.state,
                zipCodeCtu: zipData.zipCodeCtu,
            });
        }
    }

    if (isVerifiedInsurance()) {
        return {
            name: routeData.VEHICLE_DAMAGE.name,
            replace: true,
        };
    }
}
