// #region ValidationTaskEditPageLoad [C:2] [TYPE Function] [SEMANTICS validation-tasks,edit,load,task,providers]
// @BRIEF Load function for the edit validation task page — fetches existing task data and LLM providers list.
// @RELATION CALLS -> [ApiModule.getValidationTask]
// @RELATION CALLS -> [ApiModule.getLlmProviders]
// @POST Returns { task, llmProviders } or redirects to 404 on missing task.
import { api } from '$lib/api.js';
import { error } from '@sveltejs/kit';
import type { PageLoad } from './$types';

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

interface ProvidersResponse {
	providers?: unknown[];
	results?: unknown[];
	[key: string]: unknown;
}

interface LoadResult {
	task: Record<string, unknown>;
	llmProviders: unknown[];
}

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

	const [taskResult, providersResult] = await Promise.all([
		api.getValidationTask(policyId).catch(() => null) as Promise<TaskResponse | null>,
		api.getLlmProviders().catch(() => []) as Promise<unknown[] | ProvidersResponse>,
	]);

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

	const task = (taskResult as TaskResponse).task || taskResult;
	const providers = Array.isArray(providersResult)
		? providersResult
		: ((providersResult as ProvidersResponse)?.providers ?? (providersResult as ProvidersResponse)?.results ?? []);

	return { task, llmProviders: providers };
};
// #endregion ValidationTaskEditPageLoad
