---
import Layout from 'layouts/Layout.astro';
import AstroUtils from 'libs/AstroUtils';
import { getEnv } from 'libs/Env';

const pb = Astro.locals.pb

const oauths = await pb.collection('users').listAuthMethods();


console.log(JSON.stringify(oauths.authProviders[0]));

let secure = true
if (getEnv('NODE_ENV', 'production') !== 'production') {
    secure = false
}

Astro.cookies.set('provider', oauths.authProviders[0],{
		httpOnly: true,
		path: '/',
		secure: secure,
		sameSite: 'lax',
		maxAge: 365000
	})

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

await AstroUtils.wrap(async () => {
    if (Astro.request.method !== 'POST'){
        return
    }
    const form = await Astro.request.formData()
    if(form.get("type") == "userPassword"){
        const request = {
            username: form.get("username") as string,
            name: form.get("name") as string,
            email: form.get("email") as string,
            password: form.get("password") as string,
            passwordConfirm: form.get("passwordConfirm") as string,
        }
        try{
            await pb.collection('users').create(request)
            return Astro.redirect('/account/login')
        }catch(e){
            console.log(e);
        }
    }else if (form.get("type") == "discord2FA") {
        // console.log("pouet")
        // await pb.collection('user').authWithOAuth2({provider: 'discord'})
        // console.log("pouetF");
        
    }else{
        Astro.redirect("/404")
    }
})
---

<Layout title="register">
    <form id="account-creation" method="post" enctype="multipart/form-data">
        <input type="hidden" name="type" value="userPassword">
        <input required name="name" placeholder="Prénom Nom"/>
        <input required name="username" placeholder="Pseudo"/>
        <input required name="email" type="email" placeholder="Renseignez votre email" />
        <input required name="password" type="password" placeholder="Créez un mot de passe" />
        <input required name="passwordConfirm" type="password" placeholder="Confirmer votre mot de passe" />
        <button>Créer un compte</button>
    </form>

    <button id="OauthDiscord">connexion avec discord</button>
    <form method="post" enctype="multipart/form-data">
        <input type="hidden" name="type" value="discord2FA">
    </form>
    <a href={oauths.authProviders[0].authUrl + Astro.url.protocol + "//" + Astro.url.host + '/account/oauth'}>discord?</a>
</Layout>
 