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

export async function GET() {
  seedIfEmpty()
  const db = getDb()
  const devices = db.prepare('SELECT * FROM devices ORDER BY id DESC').all()
  return NextResponse.json(devices)
}

export async function POST(req: Request) {
  seedIfEmpty()
  const db = getDb()
  const body = await req.json()
  const { sn, model, type, status, firmware, production_date, customer, batch } = body
  const result = db.prepare('INSERT INTO devices (sn, model, type, status, firmware, production_date, customer, batch) VALUES (?, ?, ?, ?, ?, ?, ?, ?)').run(sn, model, type, status || '装配中', firmware || '', production_date, customer || '-', batch || '')
  return NextResponse.json({ id: result.lastInsertRowid })
}
