import { redirect } from '@sveltejs/kit';
import { createApiClient } from '$lib/shared/api.server';
import type { PageServerLoad } from './$types';

export const load: PageServerLoad = async ({ url, fetch, parent }) => {
	const layout = await parent();
	if (!layout.canBlogWrite) {
		throw redirect(303, '/geschichten');
	}

	const api = createApiClient(fetch);
	const personId = url.searchParams.get('personId');
	const documentId = url.searchParams.get('documentId');

	const [personResult, documentResult] = await Promise.all([
		personId
			? api.GET('/api/persons/{id}', { params: { path: { id: personId } } })
			: Promise.resolve(null),
		documentId
			? api.GET('/api/documents/{id}', { params: { path: { id: documentId } } })
			: Promise.resolve(null)
	]);

	// Silently ignore 404/403 to avoid leaking entity existence on unknown IDs.
	const initialPersons =
		personResult && personResult.response.ok && personResult.data ? [personResult.data] : [];
	const initialDocuments =
		documentResult && documentResult.response.ok && documentResult.data
			? [documentResult.data]
			: [];

	return { initialPersons, initialDocuments };
};
