import { json, error } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
import { saveBook, unsaveBook, updateBookShelf } from '$lib/server/pocketbase';
import type { ShelfName } from '$lib/server/pocketbase';
import { log } from '$lib/server/logger';

/**
 * POST /api/library/[slug]
 * Save a book to the user's personal library.
 */
export const POST: RequestHandler = async ({ params, locals }) => {
	const { slug } = params;
	try {
		await saveBook(locals.sessionId, slug, locals.user?.id);
	} catch (e) {
		log.error('library', 'saveBook failed', { slug, err: String(e) });
		error(500, 'Failed to save book');
	}
	return json({ ok: true });
};

/**
 * DELETE /api/library/[slug]
 * Remove a book from the user's personal library.
 */
export const DELETE: RequestHandler = async ({ params, locals }) => {
	const { slug } = params;
	try {
		await unsaveBook(locals.sessionId, slug, locals.user?.id);
	} catch (e) {
		log.error('library', 'unsaveBook failed', { slug, err: String(e) });
		error(500, 'Failed to remove book');
	}
	return json({ ok: true });
};

/**
 * PATCH /api/library/[slug]
 * Update the shelf category for a saved book.
 */
export const PATCH: RequestHandler = async ({ params, request, locals }) => {
	const { slug } = params;
	const body = await request.json().catch(() => null);
	const shelf = body?.shelf ?? '';
	const VALID = ['', 'plan_to_read', 'completed', 'dropped'];
	if (!VALID.includes(shelf)) error(400, 'invalid shelf');
	await updateBookShelf(locals.sessionId, slug, shelf as ShelfName, locals.user?.id);
	return json({ ok: true });
};
