import { OwlClient, ApiError, ValidationError, ThrowApiError } from '$lib/owlClient';
import type { ApiTrainsTrainByHeadcode } from '@owlboard/owlboard-ts';
import type { PageLoad } from './$types';

export const load: PageLoad = async ({ fetch, url }) => {
	const headcode = url.searchParams.get('h');
	let dateParam = url.searchParams.get('d');
	const toc = url.searchParams.get('t') || '';

	const date: string | Date = dateParam === '' || dateParam === null ? new Date() : dateParam;

	// Validation removed, handled by the API Client Lib

	// Declared outside of the try so that it can be used in both the try and catch blocks
	let results: ApiTrainsTrainByHeadcode.TrainByHeadcodeResponse[];

	try {
		const response = await OwlClient.trains.getByHeadcode(headcode || '', date, toc, fetch);

		let title = !!headcode ? headcode.toUpperCase() : 'Error';
		results = response.data;
		return {
			title: title,
			results: results
		};
	} catch (e: unknown) {
		ThrowApiError(e);
	}
};
