// #region ValidationHistoryPageLoad [C:2] [TYPE Function] [SEMANTICS validation-tasks,history,load,server]
// @BRIEF Load function for the validation history page — fetches runs across all tasks (v2 endpoint).
// @RELATION CALLS -> [ApiModule.fetchApi]
import { fetchApi } from '$lib/api.js';
import type { PageLoad } from './$types';

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

interface LoadResult {
	runs: unknown[];
	total: number;
	page: number;
	page_size: number;
	statusFilter?: string;
	error?: string;
}

export const load: PageLoad = async ({ url }): Promise<LoadResult> => {
	const page = parseInt(url.searchParams.get('page') || '1', 10);
	const page_size = parseInt(url.searchParams.get('page_size') || '20', 10);
	const status = url.searchParams.get('status') || undefined;

	try {
		const qs = new URLSearchParams();
		qs.append('page', String(page));
		qs.append('page_size', String(page_size));
		if (status) qs.append('status', status);

		const result: RunsResponse = await fetchApi(`/validation-tasks/runs/all?${qs.toString()}`);
		const runs = result?.items ?? result?.results ?? [];

		return {
			runs,
			total: result?.total ?? 0,
			page,
			page_size,
			statusFilter: status,
		};
	} catch (e: unknown) {
		return {
			runs: [],
			total: 0,
			page,
			page_size,
			error: e instanceof Error ? e.message : 'Failed to load runs',
		};
	}
};
// #endregion ValidationHistoryPageLoad
