import { LOCATIONS } from '$lib/locations-object.svelte';
import { ApiError, OwlClient, ValidationError } from '$lib/owlClient';
import type { PageLoad } from './$types';
import { error } from '@sveltejs/kit';

export const load: PageLoad = async ({ url, fetch }) => {
	const locId = url.searchParams.get('loc');

	if (!LOCATIONS.loaded) {
		await LOCATIONS.init();
	}
	if (!locId) {
		error(400, {
			message: 'Location not provided',
			code: 'VALIDATION'
		});
	}

	const BoardLocation = LOCATIONS.find(locId);

	if (!BoardLocation) {
		error(404, {
			message: `Location (${locId.toUpperCase()}) not found`,
			code: 'VALIDATION'
		});
	}
	const title = BoardLocation.n || BoardLocation.t || 'Live Arr/Dep';

	try {
		const boardData = await OwlClient.board.getByLocation(locId, fetch);

		return {
			title,
			BoardLocation,
			boardData
		};
	} catch (e: unknown) {
		throw e;
	}
};
