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 scrap_records ORDER BY date DESC').all() as { materials: string; [k: string]: unknown }[]
  const parsed = items.map(i => ({ ...i, materials: JSON.parse(i.materials as string) }))
  return NextResponse.json(parsed)
}

export async function POST(req: Request) {
  seedIfEmpty()
  const db = getDb()
  const body = await req.json()
  const { sn, model, reason, applicant, status, order_id, date, value, materials } = body
  const result = db.prepare('INSERT INTO scrap_records (sn, model, reason, applicant, status, order_id, date, value, materials) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)').run(sn, model, reason, applicant || '', status || '待审批', order_id || '', date, value || 0, JSON.stringify(materials || []))
  return NextResponse.json({ id: result.lastInsertRowid })
}
