<script setup lang="ts">
import { hydrate } from 'vue';
import { ZodError } from 'zod';
import { schema, type Login } from '~/schemas/login';

definePageMeta({
    usersGoesTo: '/user/profile'
});

const state = reactive<Login>({
    usernameOrEmail: '',
    password: ''
});

const { data: result, status, error, refresh } = await useFetch('/api/auth/login', {
    body: state,
    immediate: false,
    method: 'POST',
    watch: false,
    ignoreResponseError: true,
})

const usernameError = ref("");
const passwordError = ref("");
const generalError = ref("");

async function submit()
{
    if(state.password === "")
        return;

    const data = schema.safeParse(state);

    if(data.success)
    {
        await refresh()

        const login = result.value;
        if(!login || !login.success)
        {
            handleErrors(login?.error ?? error.value!);
        }
        else if(status.value === 'success' && login.success)
        {
            console.log(await navigateTo('/user/profile'));
        }
    }
    else
    {
        handleErrors(data.error);
    }
}
function handleErrors(error: Error | ZodError)
{
    if(error.hasOwnProperty('issues'))
    {
        for(const err of (error as ZodError).issues)
        {
            if(err.path.includes('username'))
            {
                usernameError.value = err.message;
            }
            if(err.path.includes('password'))
            {
                passwordError.value = err.message;
            }
        }
    }
    else
    {
        generalError.value = error?.message ?? 'Erreur inconnue.';
    }
}
</script>

<template>
    <Head>
        <Title>Se connecter</Title>
    </Head>
    <div class="site-body-center-column">
        <div class="render-container flex align-center justify-center">
            <form @submit.prevent="submit" class="input-form input-form-wide">
                <h1>Connexion</h1>
                <Input type="text" autocomplete="username" v-model="state.usernameOrEmail"
                    placeholder="" title="Nom d'utilisateur ou adresse mail" :error="usernameError" />
                <Input type="password" autocomplete="current-password" v-model="state.password"
                    placeholder="" title="Mot de passe"
                    :error="passwordError" />
                <span v-if="generalError" class="input-error">{{ generalError }}</span>
                <button>
                    <div class="loading" v-if="status === 'pending'"></div>
                    <template v-else>Se connecter</template>
                </button>
                <NuxtLink :to="{ path: `/user/register`, force: true }">Pas de compte ?</NuxtLink>
            </form>
        </div>
    </div>
</template>