<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 { currentProfile, authenticator } from '../services'
let hash = null
let hashedAccessToken = null
export default {
    name: 'VerifyView',
    async created() {
        hash = this.$route.params.hashedToken
        hashedAccessToken = this.grabCookie('siimee_access')
        try {
            this.isHashInUrl(hash)
            await this.doesAccessTokenExist(hashedAccessToken)
            await this.verifyActiveSession(hash)
            const sessionData = await this.isSessionTokenValid(hash)
            await currentProfile.login(
                sessionData.profileId,
                this.$waveui.notify,
                sessionData.accessToken,
            )
        } catch (err) {
            console.error(err)
        }
        this.$router.push('/')
    },
    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
        },
        isHashInUrl(hash) {
            if (!hash) throw new Error('URL contains no hash!')
        },
        async doesAccessTokenExist(hashedAccessToken) {
            if (!hashedAccessToken)
                throw new Error('accessToken not in cookie store!')
        },
        async verifyActiveSession(hashedToken) {
            const sessionData =
                await authenticator.verifyAuthSession(hashedToken)
            if (!sessionData.hashesMatch)
                throw new Error('Hash is not in activeSessions!')
        },
        async isSessionTokenValid(hash) {
            const sessionTokenIsValid =
                await authenticator.validateSession(hash)
            if (sessionTokenIsValid.error) {
                throw new Error(sessionTokenIsValid.error)
            } else return sessionTokenIsValid
        },
    },
}
</script>

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