<script setup>
import { ref } from 'vue';
import { useQuasar } from 'quasar';
import { useI18n } from 'vue-i18n';
import { useRouter } from 'vue-router';
import axios from 'axios';

import { useSession } from 'src/composables/useSession';
import { useLogin } from 'src/composables/useLogin';
import VnInput from 'src/components/common/VnInput.vue';
import VnOutForm from 'src/components/ui/VnOutForm.vue';

const quasar = useQuasar();
const session = useSession();
const router = useRouter();
const loginCache = useLogin();
const { t } = useI18n();

const code = ref('');
const params = loginCache.getUser().value;
if (!params.user) {
    router.push({ name: 'Login' });
}

async function onSubmit() {
    try {
        params.code = code.value;
        const { data } = await axios.post('VnUsers/validate-auth', params);
        if (!data) return;

        data.keepLogin = params.keepLogin;
        await session.setLogin(data);
    } catch (e) {
        quasar.notify({
            message: e.response?.data?.error.message,
            type: 'negative',
        });
    }
}
</script>
<template>
    <VnOutForm @submit="onSubmit" :title="t('twoFactor.insert')">
        <template #default>
            <VnInput
                v-model="code"
                :hint="t('twoFactor.explanation')"
                mask="# # # # # #"
                fill-mask
                unmasked-value
                autofocus
            >
                <template #prepend>
                    <QIcon name="lock" />
                </template>
            </VnInput>
        </template>
        <template #buttons>
            <QBtn
                :label="t('twoFactor.validate')"
                type="submit"
                color="primary"
                class="full-width q-mt-md"
                rounded
                unelevated
            />
        </template>
    </VnOutForm>
</template>
