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

import type { PageServerLoad } from './$types';
import { z } from 'zod';
import { superValidate } from 'sveltekit-superforms/server';
import { API_URL } from '$env/static/private';

const settingSchema = z.object({
	firstname: z.string({
		required_error: 'Prénom manquant'
	}),
	lastname: z.string({
		required_error: 'Nom manquant'
	}),
	pseudo: z.string({
		required_error: 'Pseudo manquant'
	})
});

export const load = (async ({ parent, locals: { user } }) => {
	await parent();

	const form = await superValidate(user, settingSchema);

	return {
		form
	};
}) satisfies PageServerLoad;

export const actions = {
	default: async ({ request, cookies }) => {
		const session = cookies.get('session');

		const form = await superValidate(request, settingSchema);

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

		const res = await fetch(`${API_URL}/user/settings`, {
			method: 'POST',
			headers: {
				Authorization: `Bearer ${session}`
			},
			body: JSON.stringify(form.data)
		});

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

		if (res.status === 400) {
			form.errors.pseudo = ['Le pseudo est déjà utilisé'];

			return fail(400, { form });
		}

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