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

type Person = components['schemas']['Person'];

export const load: PageServerLoad = async ({ url, fetch }) => {
	const api = createApiClient(fetch);
	const personIds = url.searchParams.getAll('personId');
	const documentId = url.searchParams.get('documentId') ?? undefined;

	const [listResult, ...personResults] = await Promise.all([
		api.GET('/api/geschichten', {
			params: {
				query: {
					status: 'PUBLISHED',
					personId: personIds.length ? personIds : undefined,
					documentId
				}
			}
		}),
		...personIds.map((id) => api.GET('/api/persons/{id}', { params: { path: { id } } }))
	]);

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

	const personFilters = personResults
		.filter((r) => r && r.response.ok && r.data)
		.map((r) => r!.data!) as Person[];

	return {
		geschichten: listResult.data ?? [],
		personFilters,
		documentFilter: documentId ?? null
	};
};
