import { error, fail, redirect } from '@sveltejs/kit';
import { createApiClient, extractErrorCode } from '$lib/shared/api.server';
import { getErrorMessage } from '$lib/shared/errors';
import type { DatePrecision } from '$lib/shared/utils/documentDate';
import {
	normalizePersonType,
	validatePersonFields,
	resolveValidationMessage
} from '$lib/person/person-validation';

export async function load({ locals }: { locals: App.Locals }) {
	const canWrite =
		locals.user?.groups?.some((g: { permissions: string[] }) =>
			g.permissions.includes('WRITE_ALL')
		) ?? false;
	if (!canWrite) throw error(403, 'Forbidden');
}

export const actions = {
	default: async ({ request, fetch }) => {
		const formData = await request.formData();
		const personType = normalizePersonType(formData.get('personType')?.toString());
		const title = formData.get('title')?.toString().trim() || undefined;
		const firstName = formData.get('firstName')?.toString().trim();
		const lastName = formData.get('lastName')?.toString().trim();
		const alias = formData.get('alias')?.toString().trim() || undefined;
		// Empty date input → omit date AND precision: the backend normalises the
		// absent pair to null/UNKNOWN, and a lone precision would fail the
		// coherence check (INVALID_DATE_PRECISION).
		const birthDate = formData.get('birthDate')?.toString().trim() || undefined;
		const birthDatePrecision = birthDate
			? (formData.get('birthDatePrecision')?.toString() as DatePrecision)
			: undefined;
		const deathDate = formData.get('deathDate')?.toString().trim() || undefined;
		const deathDatePrecision = deathDate
			? (formData.get('deathDatePrecision')?.toString() as DatePrecision)
			: undefined;
		const notes = formData.get('notes')?.toString().trim() || undefined;
		// Must NOT use the conditional-spread idiom for generation: G 0 is a
		// valid family-tree-root value. Always travels in the body so an
		// explicit clear (empty option) reaches the backend as null.
		const generationRaw = formData.get('generation');
		const generation =
			generationRaw == null || generationRaw.toString() === '' ? null : Number(generationRaw);

		const validationKey = validatePersonFields(personType, firstName, lastName);
		if (validationKey) {
			return fail(400, {
				error: resolveValidationMessage(validationKey),
				personType,
				title,
				firstName: firstName ?? '',
				lastName: lastName ?? '',
				alias
			});
		}

		const api = createApiClient(fetch);
		const result = await api.POST('/api/persons', {
			body: {
				personType,
				...(title ? { title } : {}),
				...(firstName ? { firstName } : {}),
				lastName: lastName!,
				...(alias ? { alias } : {}),
				...(birthDate ? { birthDate, birthDatePrecision } : {}),
				...(deathDate ? { deathDate, deathDatePrecision } : {}),
				...(notes ? { notes } : {}),
				generation
			}
		});

		if (!result.response.ok) {
			return fail(result.response.status, {
				error: getErrorMessage(extractErrorCode(result.error)),
				personType,
				title,
				firstName,
				lastName: lastName!,
				alias
			});
		}

		throw redirect(303, `/persons/${result.data!.id}`);
	}
};
