import { API_URL } from '$env/static/private';

import { fail, redirect, type Actions } from '@sveltejs/kit';

import type { PageServerLoad } from './$types';

import { superValidate } from 'sveltekit-superforms/server';
import { z } from 'zod';

const registerSchema = z.object({
	email: z
		.string()
		.email({
			message: 'Email invalide'
		})
		.trim(),
	firstname: z.string().trim(),
	lastname: z.string().trim(),
	pseudo: z.string().trim(),
	code: z
		.string({
			required_error: 'Code manquant'
		})
		.length(4, {
			message: 'Code invalide, il doit contenir 4 chiffres'
		})
		.regex(/^[0-9]+$/)
		.optional(),
	passwd: z.string().optional()
});

const confirmationSchema = z.object({
	email: z
		.string()
		.email({
			message: 'Email invalide'
		})
		.trim(),
	firstname: z.string().trim(),
	lastname: z.string().trim(),
	pseudo: z.string().trim(),
	code: z
		.string({
			required_error: 'Code manquant'
		})
		.regex(/^[0-9]{4}$/, {
			message: 'Code invalide, il doit contenir 4 chiffres'
		}),
	passwd: z.string()
});

export const load = (async ({ locals: { user } }) => {
	if (user) throw redirect(303, '/dashboard');

	const form = await superValidate(registerSchema);

	return {
		form
	};
}) satisfies PageServerLoad;

export const actions = {
	register: async ({ request }) => {
		const form = await superValidate(request, registerSchema);

		if (!form.valid) {
			return fail(400, { form });
		}

		const res = await fetch(`${API_URL}/register`, {
			method: 'POST',
			body: JSON.stringify({
				pseudo: form.data.pseudo,
				firstname: form.data.firstname,
				lastname: form.data.lastname,
				email: form.data.email
			})
		});

		if (res.ok) {
			return {
				form
			};
		}

		if (res.status === 400) {
			const { email_valid } = await res.json();

			if (!email_valid) form.errors.email = ['Un compte avec cette adresse email existe déjà'];

			return fail(400, { form });
		}

		form.errors.passwd = ["Une erreur s'est produite"];

		return fail(400, {
			form
		});
	},
	confirmation: async ({ request, cookies }) => {
		const form = await superValidate(request, confirmationSchema);

		if (!form.valid) {
			return fail(400, { form });
		}

		const res = await fetch(`${API_URL}/confirmation`, {
			method: 'POST',
			body: JSON.stringify({
				firstname: form.data.firstname,
				lastname: form.data.lastname,
				pseudo: form.data.pseudo,
				email: form.data.email,
				code: parseInt(form.data.code),
				passwd: form.data.passwd
			})
		});

		if (res.ok) {
			const token = res.headers.get('Authorization')?.split('Bearer ')[1];

			if (!token) throw new Error('No token');

			cookies.set('session', token, {
				path: '/'
			});

			throw redirect(303, '/dashboard');
		}

		form.errors.code = [`Une erreur s'est produite (${res.status} ${res.statusText})`];

		return fail(400, {
			form
		});
	}
} satisfies Actions;
