<template>
    <Form
        ref="theForm"
        @submit="onSubmit"
        @invalidSubmit="onInvalidSubmit">
    </Form>
</template>

<script>
import { Form } from 'vee-validate';
import BaseFormMixin from '@/mixins/base-form-mixin.js';
import { useMainStore } from '@/store/index.js';
import queryStrings from '@/constants/query-strings';
import getQueryStringParameter from '@/helpers/querystring-helper.js';
import { paymentMethods } from '@/constants/payment-method-constants.js';
import { submitWorkOrder } from '@/helpers/order-helper.js';
import showIssLoadingModal from '@/helpers/loading-modal-helper';

export default {
    name: 'payment-return',
    components: {
        // eslint-disable-next-line vue/no-reserved-component-names
        Form
    },
    mixins: [BaseFormMixin],
    computed: {
        creditCardToken() {
            return {
                subscriptionId: getQueryStringParameter(queryStrings.SUBSCRIPTIONID),
                expMonth: getQueryStringParameter(queryStrings.CARD_EXPIRATION_MONTH),
                expYear: getQueryStringParameter(queryStrings.CARD_EXPIRATION_YEAR),
                cardType: getQueryStringParameter(queryStrings.CARD_TYPE),
                billToPostalCode: getQueryStringParameter(queryStrings.BILL_TO_POSTAL_CODE),
                billToFirstName: getQueryStringParameter(queryStrings.BILL_TO_FIRST_NAME),
                billToLastName: getQueryStringParameter(queryStrings.BILL_TO_LAST_NAME),
                referenceNumber: getQueryStringParameter(queryStrings.REFERENCE_NUMBER),
                authCode: getQueryStringParameter(queryStrings.AUTH_CODE),
                transactionId: getQueryStringParameter(queryStrings.TRANSACTION_ID),
                transReferenceNumber: getQueryStringParameter(queryStrings.TRANS_REFERENCE_NUMBER),
                lastFour: getQueryStringParameter(queryStrings.LAST_FOUR)
            };
        }
    },
    async mounted() {
        showIssLoadingModal(true);
        const payInAdvanceError = getQueryStringParameter(queryStrings.ERROR);
        const { payInAdvanceType } = useMainStore().order.payment;

        if (payInAdvanceError) {
            console.error(`Error during payment: ${payInAdvanceError}`);
            const paymentPageNavScenario =
                payInAdvanceType === paymentMethods.CREDIT_CARD || payInAdvanceType === paymentMethods.AFTERPAY;
            if (paymentPageNavScenario) {
                this.$router.navigate(
                    this.navigationScenarios.PAY_IN_ADVANCE_CREDIT_CARD_ERROR,
                    this.$route,
                    {
                        [queryStrings.DISPLAY_PAY_IN_ADVANCE_ALERT]: payInAdvanceType
                    }
                );
            } else {
                this.$router.navigate(
                    this.navigationScenarios.PAY_IN_ADVANCE_ERROR,
                    this.$route,
                    {
                        [queryStrings.DISPLAY_PAY_IN_ADVANCE_ALERT]: true
                    }
                );
            }
        } else {
            switch (payInAdvanceType) {
                case paymentMethods.CREDIT_CARD:
                case paymentMethods.AFTERPAY:
                    await this.processCreditCardResponse();
                    break;
                case paymentMethods.PAYPAL:
                    await this.processPaypalResponse();
                    break;
                default:
                    console.log(`Unknown pay in advance type: ${payInAdvanceType}`);
                    this.$router.navigate(
                        this.navigationScenarios.PAY_IN_ADVANCE_ERROR,
                        this.$route,
                        {
                            [queryStrings.DISPLAY_PAY_IN_ADVANCE_ALERT]: true
                        }
                    );
            }
        }
    },
    methods: {
        arePagePrerequisitesValid() {
            return true;
        },
        navigateOnPayInAdvanceError() {
            this.$router.navigate(
                this.navigationScenarios.PAY_IN_ADVANCE_ERROR,
                this.$route,
                {
                    [queryStrings.DISPLAY_PAY_IN_ADVANCE_ALERT]: true
                }
            );
        },
        async processPaypalResponse() {
            const token = getQueryStringParameter(queryStrings.TOKEN);
            this.mainStore.updatePaypalToken(token);

            await this.saveAndSubmitWorkOrder();
        },
        async processCreditCardResponse() {
            const referralSeqNum = getQueryStringParameter(queryStrings.REFERRAL_SEQ_NUM);
            if (referralSeqNum !== useMainStore().order.referralSequenceNumber) {
                console.error(`error: unknown ref:${referralSeqNum} ${useMainStore().order.referralSequenceNumber}`);
                this.navigateOnPayInAdvanceError();
            } else {
                useMainStore().updateCreditCardToken(this.creditCardToken);
                await this.saveAndSubmitWorkOrder();
            }
        },
        async saveAndSubmitWorkOrder() {
            // Final work order submit after returning from pay in advance.
            useMainStore().resetSubmittedOrder();
            try {
                await submitWorkOrder({
                    pageNameToLog: 'payment-return',
                    submitAfterSave: true
                });
            } catch (error) {
                console.error(`error: response from submit work order:${error.message}`);
                this.navigateOnPayInAdvanceError();
                showIssLoadingModal(false);
                return;
            }

            showIssLoadingModal(false);
            useMainStore().createSubmittedOrder();
            this.$router.navigate(
                this.navigationScenarios.PAY_IN_ADVANCE_SUCCESS,
                this.$route
            );
        }
    }
};
</script>
