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

// Global timeline: personId is undefined, so no query params (REQ-001). SSR-first
// via createApiClient so the session cookie is forwarded; no client-side fetch
// (REQ-002). The raw payload (correspondent names/titles) is PII — never logged.
export async function load({ fetch }) {
	const api = createApiClient(fetch);
	const result = await api.GET('/api/timeline');

	if (result.response.status === 401) throw redirect(302, '/login');

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

	return { timeline: result.data! };
}
