---
import Layout from "layouts/Layout.astro";
import AstroUtils from "libs/AstroUtils";
import PocketBase from 'pocketbase'


const pb = Astro.locals.pb

if(pb.authStore.isValid){
    return Astro.redirect("/account")
}

const res = await AstroUtils.wrap(async () => {
    if (Astro.request.method !== 'POST') {
        return
    }    
    const form = await Astro.request.formData();
    const request = {
        user: form.get("username") as string,
        password: form.get("password") as string
    }

    try {
        await pb.collection('users').authWithPassword(request.user,request.password);
        return Astro.redirect("/account")
    } catch (error) {
        console.log(error)
        console.warn('user password is incorrect')
        return Astro.redirect("/account/login");// route('/account/login', {message: 'Compte invalide, valider les identifiants'})) //XXX: comprendre comment le system de route fonctionne
    }
})
---

<Layout title="login">
    <form id="account-creation" method="post" enctype="multipart/form-data">
        <input required name="username" placeholder="Pseudo ou email"/>
        <input required name="password" type="password" placeholder="Mot de passe" />
        <button>Connection</button>
    </form>
</Layout>