import type { PageServerLoad } from './$types';
import { getBooksBySlugs, allProgress, getSavedSlugs, getShelfMap } from '$lib/server/pocketbase';
import { log } from '$lib/server/logger';
import type { Book } from '$lib/server/pocketbase';

export const load: PageServerLoad = async ({ locals }) => {
	let progressList: Awaited<ReturnType<typeof allProgress>> = [];
	let savedSlugs: Set<string> = new Set();
	let shelfMap: Record<string, string> = {};

	try {
		[progressList, savedSlugs, shelfMap] = await Promise.all([
			allProgress(locals.sessionId, locals.user?.id),
			getSavedSlugs(locals.sessionId, locals.user?.id),
			getShelfMap(locals.sessionId, locals.user?.id)
		]);
	} catch (e) {
		log.error('books', 'failed to load library data', { err: String(e) });
	}

	// Fetch only the books the user actually has in their library.
	const progressSlugs = new Set(progressList.map((p) => p.slug));
	const allNeededSlugs = new Set([...progressSlugs, ...savedSlugs]);
	const books = allNeededSlugs.size > 0
		? await getBooksBySlugs(allNeededSlugs).catch(() => [] as Book[])
		: [];

	// Build a quick lookup: slug → last chapter read
	const progressMap: Record<string, number> = {};
	const progressUpdatedMap: Record<string, string> = {};
	for (const p of progressList) {
		progressMap[p.slug] = p.chapter;
		progressUpdatedMap[p.slug] = p.updated;
	}

	// Sort: books with progress first (most-recently-read), then saved-only alphabetically.
	const withProgress = books.filter((b) => progressSlugs.has(b.slug));
	const savedOnly = books
		.filter((b) => !progressSlugs.has(b.slug))
		.sort((a, b) => (a.title ?? '').localeCompare(b.title ?? ''));

	withProgress.sort((a, b) => {
		const ta = progressUpdatedMap[a.slug] ?? '';
		const tb = progressUpdatedMap[b.slug] ?? '';
		return tb.localeCompare(ta); // descending — most recently read first
	});

	return {
		books: [...withProgress, ...savedOnly],
		progressMap,
		savedSlugs: [...savedSlugs],
		shelfMap
	};
};
