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

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

export async function POST(req: Request) {
  seedIfEmpty()
  const db = getDb()
  const body = await req.json()
  const { sn, name, category, type, device_model, version, description, firmware, status, device_sn, production_date, calib_status, calib_date } = body
  const result = db.prepare('INSERT INTO materials (sn, name, category, type, device_model, version, description, firmware, status, device_sn, production_date, calib_status, calib_date) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)').run(sn, name || '', category || '', type, device_model || '', version, description || '', firmware || '-', status || '在库', device_sn || '-', production_date, calib_status || '-', calib_date || '-')
  return NextResponse.json({ id: result.lastInsertRowid })
}

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