import { json, error } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
import { getBookRating, getBookAvgRating, setBookRating } from '$lib/server/pocketbase';

export const GET: RequestHandler = async ({ params, locals }) => {
	const { slug } = params;
	const [userRating, avg] = await Promise.all([
		getBookRating(locals.sessionId, slug, locals.user?.id),
		getBookAvgRating(slug)
	]);
	return json({ userRating, avg: avg.avg, count: avg.count });
};

export const POST: RequestHandler = async ({ params, request, locals }) => {
	const { slug } = params;
	const body = await request.json().catch(() => null);
	const rating = body?.rating;
	if (typeof rating !== 'number' || rating < 1 || rating > 5) {
		error(400, 'rating must be 1–5');
	}
	await setBookRating(locals.sessionId, slug, rating, locals.user?.id);
	const avg = await getBookAvgRating(slug);
	return json({ ok: true, avg: avg.avg, count: avg.count });
};
