import { NextRequest, NextResponse } from 'next/server' import { requireLibraryAccess, requireLibraryWriteAccess } from '@/lib/auth' import { getDb } from '@/lib/db' function extractLibraryId(itemKey: string): string | null { const colonIdx = itemKey.indexOf(':') if (colonIdx === -1) return null return itemKey.slice(0, colonIdx) } export async function GET(request: NextRequest) { const { searchParams } = new URL(request.url) const itemKey = searchParams.get('itemKey') if (!itemKey) { return NextResponse.json({ error: 'itemKey is required' }, { status: 400 }) } const libraryId = extractLibraryId(itemKey) if (!libraryId) { return NextResponse.json({ error: 'Invalid itemKey' }, { status: 400 }) } const auth = await requireLibraryAccess(request, libraryId) if (auth instanceof NextResponse) return auth const db = getDb() const row = db .prepare('SELECT user_rating FROM media_items WHERE item_key = ?') .get(itemKey) as { user_rating: number | null } | undefined if (!row) { return NextResponse.json({ error: 'Item not found' }, { status: 404 }) } return NextResponse.json({ userRating: row.user_rating ?? null }) } export async function PATCH(request: NextRequest) { const body = await request.json() const { itemKey, userRating } = body as { itemKey: string; userRating: number | null } if (!itemKey) { return NextResponse.json({ error: 'itemKey is required' }, { status: 400 }) } if (userRating !== null && (typeof userRating !== 'number' || !Number.isInteger(userRating) || userRating < 1 || userRating > 5)) { return NextResponse.json({ error: 'userRating must be null or an integer 1–5' }, { status: 400 }) } const libraryId = extractLibraryId(itemKey) if (!libraryId) { return NextResponse.json({ error: 'Invalid itemKey' }, { status: 400 }) } const auth = await requireLibraryWriteAccess(request, libraryId) if (auth instanceof NextResponse) return auth const db = getDb() const result = db .prepare('UPDATE media_items SET user_rating = ? WHERE item_key = ?') .run(userRating, itemKey) if (result.changes === 0) { return NextResponse.json({ error: 'Item not found' }, { status: 404 }) } return NextResponse.json({ success: true }) }