import { getQuerystringParameter } from "@/helpers/querystring-helper";
import { queryStrings } from "@/constants/query-strings";
import store from "@/store";
import { storeMutations } from "@/constants/store-mutations";
import { updateOrCreateFunnelCookie } from "@/helpers/heritage-integration/cookie-helper";
import { getFunnelCookie } from "@/helpers/heritage-integration/cookie-helper";

export async function consumeReferralQuerystrings() {
    var referralNumber = getQuerystringParameter(queryStrings.REFERRAL_NUMBER);
    var parentAccount = getQuerystringParameter(queryStrings.PARENT_ACCOUNT);
    var correlationId = getQuerystringParameter(queryStrings.CORRELATION_ID);
    var referralDate = null;

    // If no referral number in querystring, check if heritage funnel updated last.
    // This would indicate a customer that went to heritage but did not return through the
    // normal route.  ie: left the site in search of a discount and returned without querystrings.
    const didHeritageFunnelUpdateLast = getFunnelCookie()?.DidHeritageFunnelUpdateLast;
    if (didHeritageFunnelUpdateLast && !referralNumber) {
        referralNumber = getFunnelCookie().ReferralNumber;
        parentAccount = getFunnelCookie().ReferralParentAccountNumber;
        correlationId = getFunnelCookie().ReferralCorrelationId;
        referralDate = getFunnelCookie().ReferralDate;
    }

    if (referralNumber) {
        store.commit(storeMutations.UPDATE_REFERRAL_NUMBER, referralNumber);
        store.commit(storeMutations.UPDATE_PARENT_ACCT_NUMBER, parentAccount);
        store.commit(storeMutations.UPDATE_REFERRAL_CORRELATION_ID, correlationId);

        if (referralDate) {
            store.commit(storeMutations.UPDATE_REFERRAL_DATE, referralDate);
        }
        // log(" --update cookie");
        updateOrCreateFunnelCookie();
    }
}
