import { redirect, type Actions, fail } from '@sveltejs/kit';
import type { PageServerLoad } from './$types';
import { API_URL } from '$env/static/private';

import { z } from 'zod';

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

const schema = z.object({
	pseudo: z.string().trim(),
	passwd: z.string()
});

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

		const parse = schema.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}/login`, {
			method: 'POST',
			body: JSON.stringify({
				...parse.data
			})
		});

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

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

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

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

		return fail(400, {
			errors: [{ field: 'passwd', message: "Nom d'utilisateur ou mot de passe incorrect" }]
		});
	}
} satisfies Actions;
