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') || 'GD30'
  const items = db.prepare('SELECT * FROM bom_templates WHERE model_code = ? ORDER BY id').all(modelCode) as { versions: string; [k: string]: unknown }[]
  const parsed = items.map(i => ({ ...i, versions: JSON.parse(i.versions as string) }))
  return NextResponse.json(parsed)
}

export async function POST(req: Request) {
  seedIfEmpty()
  const db = getDb()
  const body = await req.json()
  const { model_code, name, material_name, model, versions, qty, required, need_calibration, enforce_version_match } = body
  const result = db.prepare('INSERT INTO bom_templates (model_code, name, material_name, model, versions, qty, required, need_calibration, enforce_version_match) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)').run(model_code, name, material_name || '', model, JSON.stringify(versions || []), qty || 1, required ? 1 : 0, need_calibration ? 1 : 0, enforce_version_match ? 1 : 0)
  return NextResponse.json({ id: result.lastInsertRowid })
}

export async function DELETE(req: NextRequest) {
  seedIfEmpty()
  const db = getDb()
  const id = req.nextUrl.searchParams.get('id')
  if (id) db.prepare('DELETE FROM bom_templates WHERE id = ?').run(id)
  return NextResponse.json({ ok: true })
}
