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

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

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

import { z } from 'zod';

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

const registerSchema = z.object({
	email: z
		.string()
		.email({
			message: 'Email invalide'
		})
		.trim(),
	firstname: z.string().trim(),
	lastname: z.string().trim(),
	pseudo: z.string().trim()
});

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(),
	passwd: z.string()
});

export const actions = {
	register: async (event) => {
		const data = await event.request.formData();

		const parse = registerSchema.safeParse(Object.fromEntries(data.entries()));

		if (!parse.success) {
			const errors = parse.error.errors.map((error) => {
				const { path, message } = error;
				return { field: path[0], message };
			});
			return fail(400, { errors });
		}

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

		if (res.ok) {
			return {
				success: true
			};
		}

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

			const errors = [];

			if (!email_valid)
				errors.push({
					field: 'email',
					message: 'Cet email est déjà utilisé'
				});

			return fail(400, { errors });
		}

		return fail(400, {
			errors: [{ field: 'passwd', message: "Une erreur s'est produite" }]
		});
	},
	confirmation: async (event) => {
		const data = await event.request.formData();

		const parse = confirmationSchema.safeParse(Object.fromEntries(data.entries()));

		if (!parse.success) {
			const errors = parse.error.errors.map((error) => {
				const { path, message } = error;
				return { field: path[0], message };
			});
			return fail(400, { errors });
		}

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

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

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

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

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

		return fail(400, {
			errors: [{ field: 'passwd', message: "Une erreur s'est produite" }]
		});
	}
} satisfies Actions;
