<template>
    <p
    v-show="unauthorized"
    id="message">
    Unauthorized Access.
    </p>
</template>

<script>
// Supporting files
import issPageValues from '@/router/router-constants/issPage-values';
import { validateISSClientTag, validateISSClientSignature } from '@/helpers/clientauth-helper';
import { getISSCookie, updateOrCreateISSCookie } from '@/helpers/cookie-helper.js';
import { useMainStore } from '@/store';
import showIssLoadingModal from '@/helpers/loading-modal-helper';
import applicationConfig from '@/constants/application-config';

export default {
    name: 'entry-page',
    components: {
    },
    mixins: [],
    setup() {
        const mainStore = useMainStore();
        mainStore.resetISSConfigState();
        mainStore.resetPageFields();
        return { mainStore };
    },
    data() {
        return {
            unauthorized: false
        };
    },
    computed: {
    },
    async mounted() {
        const queryStringParams = this.parseQueryParms();

        const { isAuthorized, clientData, decryptedParams } = await this.validateClientTagOnEntry(queryStringParams);

        this.unauthorized = !isAuthorized;
        if (!isAuthorized) {
            // Remove the loading animation if client tag validation fails so users can see the Unauthorized Access message.
            showIssLoadingModal(false);
            return;
        }

        this.populateISSConfigValues(clientData);

        try {
            // Check cookie
            const issCookie = getISSCookie();
            if (issCookie !== null && issCookie.VehicleMake && issCookie.VehicleModel) {
                const clientParentAccountNumber = clientData.parentAccountNumber;
                const cookieParentAccountNumber = issCookie.ReferralParentAccountNumber;

                if (clientParentAccountNumber === cookieParentAccountNumber) {
                    const savedSessionTimeStamp = new Date(issCookie.SavedSessionTimeoutDate);
                    const isSavedSessionTimedOut = new Date(new Date().toUTCString()) > savedSessionTimeStamp;

                    if (!isSavedSessionTimedOut) {
                        this.mainStore.issConfig.enableContinueFromCookie = true;
                    }
                }
            } else {
                updateOrCreateISSCookie(true);
            }
        } catch {
            updateOrCreateISSCookie(true);
        }

        if (clientData.parameters?.length > 0) {
            const finalParams = this.combineClientParameters(clientData.parameters, { ...queryStringParams, ...decryptedParams });
            this.populateStoreItemsFromParams(finalParams);
        }

        this.mainStore.applicationUser.coverageAttempts = 0;
        if (
            applicationConfig.CURRENT_ENVIRONMENT === 'Localhost'
            || applicationConfig.CURRENT_ENVIRONMENT === 'Dev'
            || applicationConfig.CURRENT_ENVIRONMENT === 'SysTest'
        ) {
            this.navigateForward();
        } else {
            // Forced full location redirect here. We do not want the entry page as part of the router/flow/path history.
            window.location = `/?issPage=${issPageValues.WELCOME_PAGE}`;
        }
    },
    methods:
        {
            navigateForward() {
                this.$router.navigate(
                    this.navigationScenarios.MOVE_FORWARD_ENTRY_PAGE,
                    this.$route
                );
            },
            parseQueryParms() {
                // Dump the query string parameters into an object
                if (this.$route?.query) {
                    return Object.fromEntries(Object.entries(this.$route?.query).map(([key, value]) => [key.toLowerCase(), value]));
                }

                return {};
            },
            async validateClientTagOnEntry(queryStringParams) {
                const clientTag = queryStringParams.clienttag;
                if (!clientTag) {
                    return { isAuthorized: false };
                }

                const resp = await validateISSClientTag(clientTag);
                if (!resp) {
                    return { isAuthorized: false };
                }

                let isAuthorized = false;
                let clientData = null;
                const decryptedParams = {};

                if (resp.active && resp.accountName.length > 0) {
                    if (resp.authentication.startsWith('RSAToken')) {
                        const { token, signature } = queryStringParams;
                        const vsigResp = await validateISSClientSignature(clientTag, token, signature);
                        if (resp.authentication.includes('EncParams')) {
                            const params = new URLSearchParams(vsigResp.decryptedData);
                            for (const [key, value] of params) {
                                decryptedParams[key.toLowerCase()] = value;
                            }
                        }

                        isAuthorized = vsigResp?.valid ?? false;
                        this.mainStore.issConfig.isAuthenticated = isAuthorized;
                    } else {
                        isAuthorized = true;
                    }

                    if (isAuthorized) {
                        clientData = resp;
                    }
                }

                return { isAuthorized, clientData, decryptedParams };
            },
            populateISSConfigValues(data) {
                this.mainStore.issConfig.clientName = data.accountName;
                this.mainStore.issConfig.clientFullName = data.accountName; // Defaults to use the client name.
                this.mainStore.issConfig.clientDisplayName = data.accountName; // Defaults to use the client name.
                this.mainStore.issConfig.parentAccountNumber = data.parentAccountNumber;
                this.mainStore.issConfig.styleSheet = data.styleSheet;
                this.mainStore.issConfig.isCoverageEnabled = data.coverageEnabled;
                this.mainStore.issConfig.siteType = data.siteType;

                try {
                    if (data.clientFlags) {
                        const clientFlags = JSON.parse(data.clientFlags);

                        if (clientFlags.TPAEnabled) {
                            this.mainStore.issConfig.enableTPAFlow = true;
                        }

                        if (clientFlags.ClientFullName != null) {
                            this.mainStore.issConfig.clientFullName = clientFlags.ClientFullName;
                        }

                        if (clientFlags.ClientDisplayName != null) {
                            this.mainStore.issConfig.clientDisplayName = clientFlags.ClientDisplayName;
                        }

                        if (clientFlags.ClaimRegistrationRequired) {
                            this.mainStore.issConfig.isClaimRegistrationRequired = true;
                        }

                        if (clientFlags.EnableNoCompQuote) {
                            this.mainStore.issConfig.enableNoCompQuote = true;
                        }
                    }
                } catch (e) {
                    console.error(`Error parsing client flags: ${e}`);
                }
            },
            combineClientParameters(configParams, queryStringParams) {
                const finalParams = {};

                try {
                    const clientParams = JSON.parse(configParams);
                    for (const clientParam of clientParams) {
                        const paramName = clientParam.toLowerCase();
                        const value = queryStringParams[paramName];
                        if (value) {
                            finalParams[paramName] = value;
                        }
                    }
                } catch (e) {
                    window.console.error(`Error combining client parameters: ${e}`);
                }

                return finalParams;
            },
            populateStoreItemsFromParams(params) {
                // Populate store items from parameters.
                for (const [key, value] of Object.entries(params)) {
                    switch (key.toLowerCase()) {
                        case 'policynbr':
                        case 'policynumber':
                            this.mainStore.order.policy.policyNumber = value;
                            this.mainStore.issConfig.disabledFields.policyNumber = true;
                            break;

                        case 'policyzipcode':
                            this.mainStore.order.policy.policyZipCode = value;
                            this.mainStore.issConfig.disabledFields.policyZipCode = true;
                            break;

                        case 'dateofloss':
                        case 'lossdate':
                            // NOTE: May need some date parsing logic in here depending on client.
                            this.mainStore.order.policy.dateOfLoss = value;
                            this.mainStore.issConfig.disabledFields.dateOfLoss = true;
                            break;

                        case 'returnurl':
                        case 'successreturnurl':
                            this.mainStore.issConfig.successReturnURL = value;
                            break;

                        case 'returnurl2':
                        case 'failurereturnurl':
                            this.mainStore.issConfig.failureReturnURL = value;
                            break;

                        // Not stored
                        case 'timestamp':
                        case 'token':
                        case 'signature':
                            break;
                        default:
                    }
                }
            }
        }
};
</script>

<style lang="scss" scoped>
#message {
    text-align: center;
}
</style>
