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

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

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

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

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

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

	const form = await superValidate(schema);

	return {
		form
	};
}) satisfies PageServerLoad;

export const actions = {
	default: async ({ request, cookies }) => {
		const form = await superValidate(request, schema);

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

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

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

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

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

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

		form.errors.passwd = ["Nom d'utilisateur ou mot de passe incorrect"];

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