// #region ValidationTasksPageLoad [C:2] [TYPE Function] [SEMANTICS validation-tasks,load,server]
// @BRIEF Load function for the validation-tasks list page — fetches initial task data with pagination.
// @RELATION CALLS -> [ApiModule.getValidationTasks]
// @POST Returns { tasks, total, page, page_size, error? }
// @UX_STATE Loading -> handled client-side via skeleton rows
// @UX_STATE Error -> error field exposed, component shows retry banner
import { api } from '$lib/api.js';
import { log } from '$lib/cot-logger';
import type { PageLoad } from './$types';

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

interface LoadResult {
	tasks: unknown[];
	total: number;
	page: number;
	page_size: number;
	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 is_active = url.searchParams.get('is_active') ?? undefined;
	const environment_id = url.searchParams.get('environment_id') || undefined;
	const search = url.searchParams.get('search') || undefined;

	try {
		const result: TasksResponse = await api.getValidationTasks({
			page,
			page_size,
			...(is_active !== undefined ? { is_active: is_active === 'true' } : {}),
			...(environment_id ? { environment_id } : {}),
			...(search ? { search } : {}),
		});

		return {
			tasks: result?.items ?? result?.tasks ?? result?.results ?? [],
			total: result?.total ?? 0,
			page,
			page_size,
		};
	} catch (e: unknown) {
		const message = e instanceof Error ? e.message : 'unknown';
		log('validation-tasks', 'EXPLORE', 'Load failed', {}, message);
		return {
			tasks: [],
			total: 0,
			page,
			page_size,
			error: message || 'Failed to load validation tasks',
		};
	}
};
// #endregion ValidationTasksPageLoad
