<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 { getCartTotal } from '@/helpers/cart-helper';
import { submitWorkOrder } from '@/helpers/order-helper.js';
import submitType from '@/constants/submit-type';
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 { paymentMethod } = useMainStore().order.payment;

        if (payInAdvanceError) {
            console.error(`Error during payment: ${payInAdvanceError}`);
            const paymentPageNavScenario =
                paymentMethod === paymentMethods.CREDIT_CARD || paymentMethod === paymentMethods.AFTERPAY;
            if (paymentPageNavScenario) {
                this.$router.navigate(
                    this.navigationScenarios.PAY_IN_ADVANCE_CREDIT_CARD_ERROR,
                    this.$route,
                    {
                        [queryStrings.DISPLAY_PAY_IN_ADVANCE_ALERT]: paymentMethod
                    }
                );
            } else {
                this.$router.navigate(
                    this.navigationScenarios.PAY_IN_ADVANCE_ERROR,
                    this.$route,
                    {
                        [queryStrings.DISPLAY_PAY_IN_ADVANCE_ALERT]: true
                    }
                );
            }
        } else {
            switch (paymentMethod) {
                case paymentMethods.CREDIT_CARD:
                case paymentMethods.AFTERPAY:
                case paymentMethods.APPLEPAY:
                    await this.processCreditCardResponse();
                    break;
                case paymentMethods.PAYPAL:
                    await this.processPaypalResponse();
                    break;
                default:
                    console.log(`Unknown payment method: ${paymentMethod}`);
                    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);
            const cartTotal = getCartTotal(useMainStore().order);
            useMainStore().order.payment.nextGenSettledAmount = cartTotal;
            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);
                const cartTotal = getCartTotal(useMainStore().order);
                useMainStore().order.payment.nextGenSettledAmount = cartTotal;
                await this.saveAndSubmitWorkOrder();
            }
        },
        async saveAndSubmitWorkOrder() {
            // Final work order submit after returning from pay in advance.
            try {
                await submitWorkOrder({ submitType: submitType.SAFELITE });
            } catch (error) {
                console.error(`error: response from submit work order:${error.message}`);
                this.navigateOnPayInAdvanceError();
                return;
            }

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