<script setup lang="ts">
import { ZodError } from 'zod';
import { schema, type Registration } from '~/schemas/registration';

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

const state = reactive<Registration>({
    username: '',
    email: '',
    password: ''
});

const confirmPassword = ref("");

const checkedLength = computed(() => state.password.length >= 8 && state.password.length <= 128);
const checkedLowerUpper = computed(() => state.password.toLowerCase() !== state.password && state.password.toUpperCase() !== state.password);
const checkedDigit = computed(() => /[0-9]/.test(state.password));
const checkedSymbol = computed(() => " !\"#$%&'()*+,-./:;<=>?@[]^_`{|}~".split("").some(e => state.password.includes(e)));

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

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

async function submit()
{
    if(state.password === "" || state.password !== confirmPassword.value)
        return;

    const data = schema.safeParse(state);

    if(data.success)
    {
        await execute()

        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('email'))
            {
                emailError.value = err.message;
            }
        }
    }
    else
    {
        generalError.value = error?.message ?? 'Erreur inconnue.';
    }
}
</script>

<template>

    <Head>
        <Title>S'inscrire</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>Inscription</h1>
                <Input type="text" autocomplete="username" v-model="state.username"
                    placeholder="Entrez un nom d'utiliateur" title="Nom d'utilisateur" :error="usernameError" />
                <Input type="text" autocomplete="email" v-model="state.email" placeholder="Entrez une addresse mail"
                    title="Adresse mail" :error="emailError" />
                <Input type="password" autocomplete="new-password" v-model="state.password"
                    placeholder="Entrez un mot de passe" title="Mot de passe"
                    :error="!(checkedLength && checkedLowerUpper && checkedDigit && checkedSymbol)" />
                <div class="password-validation-group">
                    <span class="password-validation-title">Votre mot de passe doit respecter les critères suivants
                        :</span>
                    <span class="password-validation-item" :class="{'validation-error': !checkedLength}">Entre 8 et 128
                        caractères</span>
                    <span class="password-validation-item" :class="{'validation-error': !checkedLowerUpper}">Au moins
                        une minuscule et une majuscule</span>
                    <span class="password-validation-item" :class="{'validation-error': !checkedDigit}">Au moins un
                        chiffre</span>
                    <span class="password-validation-item" :class="{'validation-error': !checkedSymbol}">Au moins un
                        caractère spécial parmis la liste suivante:
                        <pre>! " # $ % & ' ( ) * + , - . / : ; < = > ? @ [ ] ^ _ ` { | } ~</pre>
                    </span>
                </div>
                <Input type="password" v-model="confirmPassword" placeholder="Confirmer le mot de passe"
                    title="Confirmer le mot de passe"
                    autocomplete="new-password"
                    :error="confirmPassword === '' || confirmPassword === state.password ? '' : 'Les mots de passe saisies ne sont pas identique'" />
                <span v-if="generalError" class="input-error">{{ generalError }}</span>
                <button><div v-if="status === 'pending'" class="loading"></div><template v-else>S'inscrire</template></button>
                <NuxtLink :to="{ path: `/user/login`, force: true }">Se connecter</NuxtLink>
            </form>
        </div>
    </div>
</template>