// #region DashboardValidationLoad [C:2] [TYPE Function] [SEMANTICS dashboards,validation,load,server]
// @BRIEF Load function for the dashboard validation runs page — fetches runs filtered by dashboard_id and environment_id.
// @RELATION CALLS -> [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;
	dashboardId: string;
	envId: string;
	error?: string;
}

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

	if (!envId) {
		return {
			runs: [],
			total: 0,
			page,
			page_size,
			dashboardId,
			envId,
			error: 'Environment ID (env_id) is required',
		};
	}

	try {
		const qs = new URLSearchParams();
		qs.append('dashboard_id', dashboardId);
		qs.append('environment_id', envId);
		qs.append('page', String(page));
		qs.append('page_size', String(page_size));

		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,
			dashboardId,
			envId,
		};
	} catch (e: unknown) {
		return {
			runs: [],
			total: 0,
			page,
			page_size,
			dashboardId,
			envId,
			error: e instanceof Error ? e.message : 'Failed to load validation runs',
		};
	}
};
// #endregion DashboardValidationLoad
