import { error, fail, redirect } from '@sveltejs/kit';
import type { PageServerLoad, Actions } from './$types';
import { createApiClient, extractErrorCode } from '$lib/shared/api.server';
import { getErrorMessage } from '$lib/shared/errors';

export const load: PageServerLoad = async ({ fetch, locals }) => {
	const user = locals.user;
	const hasAdmin = user?.groups?.some((g: { permissions: string[] }) =>
		g.permissions.includes('ADMIN')
	);
	if (!hasAdmin) throw error(403, getErrorMessage('FORBIDDEN'));

	const api = createApiClient(fetch);
	const groupsResult = await api.GET('/api/groups');

	return { groups: groupsResult.data ?? [] };
};

export const actions: Actions = {
	default: async ({ request, fetch }) => {
		const data = await request.formData();
		const api = createApiClient(fetch);

		const birthDateRaw = data.get('birthDate') as string;
		const result = await api.POST('/api/users', {
			body: {
				email: data.get('email') as string,
				initialPassword: data.get('password') as string,
				groupIds: data.getAll('groupIds') as string[],
				firstName: (data.get('firstName') as string) || null,
				lastName: (data.get('lastName') as string) || null,
				birthDate: birthDateRaw || null,
				contact: (data.get('contact') as string) || null
			}
		});

		if (!result.response.ok) {
			return fail(result.response.status, {
				error: getErrorMessage(extractErrorCode(result.error))
			});
		}

		throw redirect(303, '/admin/users');
	}
};
