import { NextRequest, NextResponse } from 'next/server' import { requireAdmin } from '@/lib/auth' import { getDb } from '@/lib/db' export async function PATCH(request: NextRequest) { const auth = await requireAdmin(request) if (auth instanceof NextResponse) return auth const body = await request.json() const { itemKey, title, year, plot, genres } = body as { itemKey: string title?: string year?: number | null plot?: string | null genres?: string[] } if (!itemKey) { return NextResponse.json({ error: 'Missing itemKey' }, { status: 400 }) } const db = getDb() const row = db.prepare('SELECT metadata FROM media_items WHERE item_key = ?').get(itemKey) as { metadata: string | null } | undefined if (!row) { return NextResponse.json({ error: 'Item not found' }, { status: 404 }) } const sets: string[] = [] const params: Record = { item_key: itemKey } if (title !== undefined) { sets.push('title = @title') params.title = title } if (year !== undefined) { sets.push('year = @year') params.year = year } if (plot !== undefined) { sets.push('plot = @plot') params.plot = plot } if (genres !== undefined) { sets.push('genres = @genres') params.genres = JSON.stringify(genres) } // Always mark as manually edited in the metadata blob const existingMeta = row.metadata ? JSON.parse(row.metadata) : {} existingMeta.manuallyEdited = true sets.push('metadata = @metadata') params.metadata = JSON.stringify(existingMeta) if (sets.length === 0) { return NextResponse.json({ error: 'No fields to update' }, { status: 400 }) } db.prepare(`UPDATE media_items SET ${sets.join(', ')} WHERE item_key = @item_key`).run(params) return NextResponse.json({ success: true }) }