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',
			owlCode: 'NO_LOCATION_IN_PATH'
		});
	}

	const BoardLocation = LOCATIONS.find(locId);

	if (!BoardLocation) {
		error(404, {
			message: `Location (${locId.toUpperCase()}) not found`,
			owlCode: 'INVALID_LOCATION_CODE'
		});
	}
	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) {
		if (
			e instanceof TypeError &&
			(e.message == 'Failed to fetch' || e.message.includes('network'))
		) {
			throw error(503, {
				message: 'Network error: Please check your connection',
				owlCode: 'NETWORK_DISCONNECTED'
			});
		}
		if (e instanceof ValidationError) {
			throw error(400, { message: e.message, owlCode: 'VALIDATION_ERROR' });
		} else if (e instanceof ApiError) {
			// If the API returns 404, it means the backend doesn't recognize this CRS/TIPLOC
			if (e.code === 'NOT_FOUND') {
				throw error(404, {
					message: `Location (${locId.toUpperCase()}) is not recognized by the server.`,
					owlCode: 'LOCATION_NOT_IN_BACKEND'
				});
			}
			throw error(e.status, { message: e.message, owlCode: 'API_ERROR' });
		} else if (e instanceof Error) {
			throw error(500, { message: e.message, owlCode: 'GEN_ERROR' });
		}

		throw error(500, { message: 'Unexpected error', owlCode: 'UNKNOWN_ERR' });
	}
};
