import { error } from '@sveltejs/kit';

export async function load({ fetch, params }) {
	// Fail loudly. The previous version caught everything and returned
	// {status, error}, which nothing consumed — so a missing book produced a
	// reader that sat on its spinner forever.
	const response = await fetch(`/api/books/${params.bookId}`);

	if (!response.ok) {
		error(response.status, 'This book could not be loaded.');
	}

	const book = await response.json();
	const file = book.files?.find((f: { id: number }) => String(f.id) === params.fileId);

	if (!file) {
		error(404, 'That file is not part of this book.');
	}

	return {
		title: book.title,
		filename: file.filename,
		// epub_cfi and percentage are what BookProgressRead actually carries;
		// this used to read progress.epub_loc and progress.progress, so resuming
		// never worked.
		initialEpubLoc: book.progress?.epub_cfi ?? null,
		initialProgress: book.progress?.percentage ?? 0
	};
}
