<template lang="pug">
.wait-message
    p.verify-message Thanks for authenticating your email!
    p.verify-message Please give us a moment to redirect you back to the survey
</template>

<script>
import { Authenticator } from '../services/auth.service.js'
export default {
    name: 'VerifyView',
    data: () => ({
        authenticator: {},
    }),
    async created() {
        this.authenticator = new Authenticator()
        const hashEmail = this.$route.params.email
        const hashesMatch = await this.authenticator.verifyAuthEmail(hashEmail)
        const siimeeToken = this.grabToken(document.cookie)

        // TODO: remove once currentProfile is established and user is logged in...
        // NOTE: another siimee_jwt cookie for onboarding path instead of verify
        document.cookie = `siimee_jwt=${siimeeToken}; path=/onboarding`

        const jwt = await this.authenticator.validateJwt(siimeeToken)

        if (jwt.isValid && hashesMatch) {
            // TODO: set jwt.payload.profile_id as siimee_profile_id
            // remove answers, will query db at SurveyCompleteView.vue
            const siimeeAnswers = JSON.stringify(jwt.payload)
            document.cookie = `siimee_answered=${siimeeAnswers} ; path=/onboarding`
            this.$router.push('/onboarding')
        }
        // else {
        // render ERROR message above or redirect to 404 (or both?)
    },
    methods: {
        grabToken(cookieString) {
            const cookies = cookieString.split('; ').reduce((prev, current) => {
                const [name, ...value] = current.split('=')
                prev[name] = value.join('=')
                return prev
            }, {})
            return 'siimee_jwt' in cookies ? cookies['siimee_jwt'] : undefined
        },
    },
}
</script>

<style>
.wait-message {
    margin: 5rem auto;
    text-align: center;
    width: 90%;
    max-width: 35rem;
    font-size: 150%;
    font-weight: bold;
}
</style>
