import { BOOK_PRESETS, presetQuery } from '$lib/presets';

export async function load({ params, fetch }) {
	try {
		// The shelves are the built-in presets, fetched in parallel rather than
		// one after another as before.
		const responses = await Promise.all(
			BOOK_PRESETS.map(async (preset) => {
				const response = await fetch(`/api/books?${presetQuery(preset, params.libraryId)}`);
				const result = await response.json();
				return [preset.id, result['items'] ?? []] as const;
			})
		);

		const shelves = Object.fromEntries(responses);

		return {
			presets: BOOK_PRESETS,
			shelves
		};
	} catch (error) {
		console.error('Error fetching books from library: ', error);

		// Same shape as the success path, so the page renders its empty state
		// instead of the caller having to guard every field. The previous
		// {status, error} return was consumed by nothing.
		return {
			presets: BOOK_PRESETS,
			shelves: Object.fromEntries(BOOK_PRESETS.map((preset) => [preset.id, []]))
		};
	}
}
