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

export async function POST(req: Request) {
  seedIfEmpty()
  const db = getDb()
  const body = await req.json()
  const { id, sn, fault_type, status, priority, assignee, create_date, description } = body
  db.prepare('INSERT INTO repair_orders (id, sn, fault_type, status, priority, assignee, create_date, description) VALUES (?, ?, ?, ?, ?, ?, ?, ?)').run(id, sn, fault_type, status || '待处理', priority || '中', assignee || '', create_date, description || '')
  return NextResponse.json({ ok: true })
}
