import { NextRequest, NextResponse } from 'next/server' import { requireAdmin } from '@/lib/auth' import { getLibrary } from '@/lib/libraries' import { getDb } from '@/lib/db' export async function POST( request: NextRequest, { params }: { params: Promise<{ id: string }> }, ) { const auth = await requireAdmin(request) if (auth instanceof NextResponse) return auth const { id: libraryId } = await params const library = getLibrary(libraryId) if (!library) { return NextResponse.json({ error: 'Library not found' }, { status: 404 }) } if (library.type !== 'comics') { return NextResponse.json({ error: 'Only comics libraries support bulk rename' }, { status: 400 }) } const body = await request.json() const { pattern, preview } = body as { pattern: string; preview?: boolean } if (!pattern || typeof pattern !== 'string') { return NextResponse.json({ error: 'Pattern is required' }, { status: 400 }) } // Validate regex let regex: RegExp try { regex = new RegExp(pattern, 'g') } catch { return NextResponse.json({ error: 'Invalid regex pattern' }, { status: 400 }) } const db = getDb() const rows = db .prepare( `SELECT item_key, title FROM media_items WHERE library_id = ? AND item_type IN ('comic_series', 'comic_issue')` ) .all(libraryId) as { item_key: string; title: string }[] const changes: { itemKey: string; oldTitle: string; newTitle: string }[] = [] for (const row of rows) { // Reset lastIndex since we reuse the regex with 'g' flag regex.lastIndex = 0 const newTitle = row.title.replace(regex, '').trim() if (newTitle && newTitle !== row.title) { changes.push({ itemKey: row.item_key, oldTitle: row.title, newTitle }) } } if (preview) { return NextResponse.json({ changes }) } // Apply const stmt = db.prepare('UPDATE media_items SET title = ? WHERE item_key = ?') db.transaction(() => { for (const c of changes) { stmt.run(c.newTitle, c.itemKey) } })() return NextResponse.json({ updated: changes.length }) }