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

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;

	if (!headcode) {
		throw error(400, {
			message: 'Headcode not provided',
			owlCode: 'INVALID_DATA'
		});
	}

	// 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);

		results = response.data;
		return {
			title: headcode.toUpperCase(),
			results: results
		};
	} catch (e: unknown) {
		if (e instanceof ValidationError) {
			throw error(400, {
				message: e.message,
				owlCode: 'VALIDATION_ERROR'
			});
		} else if (e instanceof ApiError) {
			// Check if NO_RESULTS error, and return empty array if that is the case
			if (e.code === 'NOT_FOUND') {
				return {
					title: headcode.toUpperCase(),
					results: []
				};
			} else {
				throw error(e.status, {
					message: e.message,
					owlCode: 'API_ERROR'
				});
			}
		} else if (e instanceof Error) {
			throw error(500, {
				message: e.message,
				owlCode: 'GEN_ERROR'
			});
		} else {
			throw error(500, {
				message: 'Unexpected error',
				owlCode: 'UNKNOWN_ERR'
			});
		}
	}
};
