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

export async function GET() {
  seedIfEmpty()
  const db = getDb()
  const items = db.prepare('SELECT * FROM board_types ORDER BY id').all() as { device_models: string; [k: string]: unknown }[]
  const parsed = items.map(i => ({ ...i, device_models: undefined, deviceModels: JSON.parse(i.device_models as string) }))
  return NextResponse.json(parsed)
}

export async function POST(req: Request) {
  seedIfEmpty()
  const db = getDb()
  const body = await req.json()
  const { name, category, device_models, deviceModels, description, status } = body
  const models = device_models || deviceModels || []
  const result = db.prepare('INSERT INTO board_types (name, category, device_models, description, status) VALUES (?, ?, ?, ?, ?)').run(name, category, JSON.stringify(models), description || '', status || '启用')
  return NextResponse.json({ id: result.lastInsertRowid })
}

export async function PUT(req: Request) {
  seedIfEmpty()
  const db = getDb()
  const body = await req.json()
  const { id, name, category, device_models, deviceModels, description, status } = body
  const models = device_models || deviceModels || []
  db.prepare('UPDATE board_types SET name=?, category=?, device_models=?, description=?, status=? WHERE id=?').run(name, category, JSON.stringify(models), description || '', status || '启用', id)
  return NextResponse.json({ ok: true })
}

export async function DELETE(req: Request) {
  seedIfEmpty()
  const db = getDb()
  const { id } = await req.json()
  db.prepare('DELETE FROM board_types WHERE id = ?').run(id)
  return NextResponse.json({ ok: true })
}
