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 personResult = personId
		? await api.GET('/api/persons/{id}', { params: { path: { id: personId } } })
		: null;

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

	// Validate ?type against the known union — prevents unexpected strings from reaching the API.
	// Security note: strict equality rejects encoded variants (e.g. STORY%00JOURNEY) and
	// only the FIRST value is returned by searchParams.get() on repeated params.
	const rawType = url.searchParams.get('type');
	const selectedType: 'STORY' | 'JOURNEY' | null =
		rawType === 'STORY' || rawType === 'JOURNEY' ? rawType : null;

	return { initialPersons, selectedType };
};
