// #region ValidationTaskDetailPageLoad [C:2] [TYPE Module] [SEMANTICS validation, task, detail, load]
// @BRIEF SvelteKit load function for the validation task detail page — fetches task metadata and paginated run history.
// @RELATION CALLS -> [ValidationApi]
// @PRE policyId route param is a non-empty string.
// @POST Returns { task, runs, total } or redirects to 404 on missing task.
import { getValidationTask, getValidationRuns } from '$lib/api.js';
import { error } from '@sveltejs/kit';
import type { PageLoad } from './$types';

interface TaskResponse {
	task?: Record<string, unknown>;
	[key: string]: unknown;
}

interface RunsResponse {
	results?: unknown[];
	items?: unknown[];
	total?: number;
	count?: number;
}

interface LoadResult {
	task: Record<string, unknown>;
	runs: unknown[];
	total: number;
}

export const load: PageLoad = async ({ params }): Promise<LoadResult> => {
	const { policyId } = params as { policyId: string };

	const [taskRes, runsRes] = await Promise.all([
		getValidationTask(policyId).catch(() => null) as Promise<TaskResponse | null>,
		getValidationRuns(policyId, { page: 1, page_size: 20 }).catch(() => ({ results: [], total: 0 })) as Promise<RunsResponse>,
	]);

	if (!taskRes) {
		error(404, 'Task not found');
	}

	const task = (taskRes as TaskResponse).task || taskRes;
	const runs = Array.isArray(runsRes) ? runsRes : ((runsRes as RunsResponse)?.results || (runsRes as RunsResponse)?.items || []);
	const total = (runsRes as RunsResponse)?.total || (runsRes as RunsResponse)?.count || runs.length;

	return { task, runs, total };
};
// #endregion ValidationTaskDetailPageLoad
