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 material_categories ORDER BY sort_order').all()
  return NextResponse.json(items)
}

export async function POST(req: Request) {
  seedIfEmpty()
  const db = getDb()
  const body = await req.json()
  const { name, description, has_firmware, has_calibration, sort_order, status } = body
  const result = db.prepare('INSERT INTO material_categories (name, description, has_firmware, has_calibration, sort_order, status) VALUES (?, ?, ?, ?, ?, ?)').run(name, description || '', has_firmware ? 1 : 0, has_calibration ? 1 : 0, sort_order || 0, 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, description, has_firmware, has_calibration, sort_order, status } = body
  db.prepare('UPDATE material_categories SET name=?, description=?, has_firmware=?, has_calibration=?, sort_order=?, status=? WHERE id=?').run(name, description || '', has_firmware ? 1 : 0, has_calibration ? 1 : 0, sort_order || 0, 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 material_categories WHERE id = ?').run(id)
  return NextResponse.json({ ok: true })
}
