---
import Layout from 'layouts/PageLayout.astro';
//import Layout from 'layouts/Layout.astro';
import AstroUtils from "libs/AstroUtils";
import PocketBase from 'pocketbase'
import ContactUs from 'components/widgets/Contact.astro';
import CallToAction from 'components/widgets/CallToAction.astro';
import Oauth from 'components/Oauth.astro';

const pb = Astro.locals.pb

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


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
    }
})

const metadata = {
  title: 'Login',
  ignoreTitleTemplate: true,
};
---

<Layout metadata={metadata}>
  <ContactUs
  formid="login"
  title="Connexion"
  subtitle="Connectez vous pour sauvegardez vos recherche"
  button='Connexion'
  method='post'
  enctype="multipart/form-data"
  inputs={[
    {
      type: 'text',
      name: 'username',
      label: 'Nom d\'utilisateur ou e-mail',
      placeholder: "michel@example.com"
    },
    {
      type: "password",
      name: "password"
    }
  ]}
  />
  <Oauth/>
</Layout>
