import { error } from '@sveltejs/kit';
import { createApiClient, extractErrorCode } from '$lib/shared/api.server';
import { getErrorMessage } from '$lib/shared/errors';

export async function load({ params, fetch, locals }) {
	const { id } = params;
	const api = createApiClient(fetch);

	const canWrite =
		(locals.user as { groups?: { permissions: string[] }[] } | undefined)?.groups?.some((g) =>
			g.permissions.includes('WRITE_ALL')
		) ?? false;

	const [
		personResult,
		sentDocsResult,
		receivedDocsResult,
		aliasesResult,
		relsResult,
		inferredResult,
		geschichtenResult
	] = await Promise.all([
		api.GET('/api/persons/{id}', { params: { path: { id } } }),
		api.GET('/api/persons/{id}/documents', { params: { path: { id } } }),
		api.GET('/api/persons/{id}/received-documents', { params: { path: { id } } }),
		api.GET('/api/persons/{id}/aliases', { params: { path: { id } } }),
		api.GET('/api/persons/{id}/relationships', { params: { path: { id } } }),
		api.GET('/api/persons/{id}/inferred-relationships', { params: { path: { id } } }),
		api.GET('/api/geschichten', {
			params: { query: { status: 'PUBLISHED', personId: id } }
		})
	]);

	if (!personResult.response.ok) {
		throw error(
			personResult.response.status,
			getErrorMessage(extractErrorCode(personResult.error))
		);
	}

	return {
		person: personResult.data!,
		sentDocuments: sentDocsResult.data ?? [],
		receivedDocuments: receivedDocsResult.data ?? [],
		aliases: aliasesResult.data ?? [],
		relationships: relsResult.data ?? [],
		inferredRelationships: inferredResult.data ?? [],
		geschichten: geschichtenResult.data ?? [],
		canWrite
	};
}
