<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: {},
        answers: {},
        hash: undefined,
        sessionToken: undefined,
    }),
    async created() {
        this.authenticator = new Authenticator()
        this.hash = this.$route.params.email
        this.sessionToken = this.grabCookie('siimee_session')
        try {
            this.isHashInUrl(this.hash)
            this.doesEmailMatch(this.hash)
            this.doesSessionTokenExist(this.sessionToken)
            this.isSessionTokenValid(this.sessionToken)
        } catch (err) {
            console.error(err)
        }
        this.$router.push('/onboarding')
    },
    methods: {
        grabCookie(cookieKey) {
            const cookies = document.cookie
                .split('; ')
                .reduce((prev, current) => {
                    const [name, ...value] = current.split('=')
                    prev[name] = value.join('=')
                    return prev
                }, {})
            return `${cookieKey}` in cookies
                ? cookies[`${cookieKey}`]
                : undefined
        },
        async getAccessToken(payload) {
            const accessToken = await this.authenticator.getJwt({
                payload,
                expires: 60 * 3,
            })
            document.cookie = `siimee_access=${accessToken}; max-age=600; path=/; secure`
        },
        isHashInUrl(hash) {
            if (!hash) throw new Error('URL contains no hash!')
        },
        async doesEmailMatch(hashEmail) {
            const hashesMatch = await this.authenticator.verifyAuthEmail(
                hashEmail,
            )
            if (!hashesMatch) throw new Error('Hash is not in registry!')
        },
        async doesSessionTokenExist(sessionToken) {
            if (!sessionToken)
                throw new Error('sessionToken not in cookie store!')
        },
        async isSessionTokenValid(sessionToken) {
            const sessionTokenIsValid =
                await this.authenticator.validateSession(sessionToken)
            if (sessionTokenIsValid.error) {
                throw new Error(sessionTokenIsValid.error)
            } else {
                // TODO: Does accessToken need sessionToken data?
                await this.getAccessToken(...this.sessionToken)
            }
        },
    },
}
</script>

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