import { json, error } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
import {
	getUserByUsername,
	getUserPublicLibrary,
	getUserCurrentlyReading
} from '$lib/server/pocketbase';
import { log } from '$lib/server/logger';

/**
 * GET /api/users/[username]/library
 * Returns the public library + currently-reading list for a user.
 * Does not require authentication — all data is public.
 */
export const GET: RequestHandler = async ({ params }) => {
	const { username } = params;

	const user = await getUserByUsername(username).catch(() => null);
	if (!user) error(404, `User "${username}" not found`);

	try {
		const [currentlyReading, library] = await Promise.all([
			getUserCurrentlyReading(user.id),
			getUserPublicLibrary(user.id)
		]);

		return json({
			currently_reading: currentlyReading.map((item) => ({
				book: item.book,
				last_chapter: item.chapter,
				saved: false
			})),
			library: library.map((item) => ({
				book: item.book,
				last_chapter: item.chapter,
				saved: item.saved
			}))
		});
	} catch (e) {
		log.error('api/users/library', 'failed to load library', { username, err: String(e) });
		error(500, 'Failed to load library');
	}
};
