import { NextRequest, NextResponse } from 'next/server'
import { getDb } from '@/lib/db'
import { seedIfEmpty } from '@/lib/seed'

export async function GET(req: NextRequest) {
  seedIfEmpty()
  const db = getDb()
  const modelCode = req.nextUrl.searchParams.get('model') || ''
  if (modelCode) {
    const items = db.prepare('SELECT * FROM checklist_templates WHERE model_code = ? ORDER BY sort_order').all(modelCode)
    return NextResponse.json(items)
  }
  // Return grouped by model_code
  const all = db.prepare('SELECT * FROM checklist_templates ORDER BY model_code, sort_order').all() as { model_code: string; id: number; name: string; required: number; sort_order: number }[]
  const grouped: Record<string, typeof all> = {}
  for (const item of all) {
    if (!grouped[item.model_code]) grouped[item.model_code] = []
    grouped[item.model_code].push(item)
  }
  return NextResponse.json(grouped)
}

export async function POST(req: Request) {
  seedIfEmpty()
  const db = getDb()
  const body = await req.json()
  const { model_code, items } = body as { model_code: string; items: { name: string; required: boolean }[] }
  const insert = db.prepare('INSERT INTO checklist_templates (model_code, name, required, sort_order) VALUES (?, ?, ?, ?)')
  for (let i = 0; i < items.length; i++) {
    if (items[i].name.trim()) {
      insert.run(model_code, items[i].name.trim(), items[i].required ? 1 : 0, i)
    }
  }
  return NextResponse.json({ ok: true })
}
