import { listAuthors } from '$lib/api/author.remote.js';
import { listBooks } from '$lib/api/book.remote.js';
import { listBookshelves } from '$lib/api/bookshelf.remote.js';
import { listPublishers } from '$lib/api/publisher.remote.js';
import { listTags } from '$lib/api/tag.remote.js';
import { redirect } from '@sveltejs/kit';

export async function load({ params, url, depends }) {
	depends('app:books');

	// Ensure the default parameters exist
	const searchParams = url.searchParams;

	const defaults = {
		orderBy: 'title',
		sortOrder: 'asc'
	};

	let needsRedirect = false;
	const newParams = new URLSearchParams(searchParams);

	// Check and set defaults only if missing
	for (const [key, value] of Object.entries(defaults)) {
		if (!searchParams.has(key)) {
			newParams.set(key, value);
			needsRedirect = true;
		}
	}

	if (needsRedirect) {
		throw redirect(302, `${url.pathname}?${newParams.toString()}`);
	}

	// Convert searchParams to object, preserving arrays
	const paramsObject: Record<string, string | string[]> = {};
	for (const [key, value] of searchParams.entries()) {
		const allValues = searchParams.getAll(key);
		paramsObject[key] = allValues.length > 1 ? allValues : value;
	}

	const [books, authors, publishers, tags, bookshelves] = await Promise.all([
		listBooks({
			libraries: [params.libraryId],
			...paramsObject,
			pageSize: 50
		}),
		listAuthors({ libraries: [params.libraryId], pageSize: 500 }),
		listPublishers({ libraries: [params.libraryId], pageSize: 500 }),
		listTags({ libraries: [params.libraryId], pageSize: 500 }),
		listBookshelves({ libraries: [params.libraryId], pageSize: 500 })
	]);

	return {
		books,
		authors,
		publishers,
		tags,
		bookshelves
	};
}
