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

export async function load({ url, fetch, locals }) {
	const q = url.searchParams.get('q') || '';
	const api = createApiClient(fetch);

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

	const [personsResult, statsResult] = await Promise.all([
		api.GET('/api/persons', { params: { query: { q: q || undefined } } }),
		api.GET('/api/stats', {})
	]);

	if (!personsResult.response.ok) {
		throw error(personsResult.response.status, getErrorMessage(undefined));
	}

	const stats = statsResult.response.ok
		? {
				totalPersons: statsResult.data!.totalPersons ?? 0,
				totalDocuments: statsResult.data!.totalDocuments ?? 0
			}
		: { totalPersons: 0, totalDocuments: 0 };

	return { persons: personsResult.data!, stats, q, canWrite };
}
