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

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

export async function POST(req: Request) {
  seedIfEmpty()
  const db = getDb()
  const body = await req.json()
  const { name, code, status, description } = body
  const date = new Date().toISOString().split('T')[0]
  const result = db.prepare('INSERT INTO device_models (name, code, status, description, create_date) VALUES (?, ?, ?, ?, ?)').run(name, code, status || '在产', description || '', date)
  return NextResponse.json({ id: result.lastInsertRowid })
}

export async function PUT(req: Request) {
  seedIfEmpty()
  const db = getDb()
  const body = await req.json()
  const { id, status } = body
  db.prepare('UPDATE device_models SET status = ? WHERE id = ?').run(status, id)
  return NextResponse.json({ ok: true })
}
