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

export async function POST(req: Request) {
  seedIfEmpty()
  const db = getDb()
  const body = await req.json()
  const { name, model, version, status, voltage, current, duty_cycle, pulse_width, channels, sample_rate, voltage_range, waveform, ssid } = body
  const now = new Date().toISOString().replace('T', ' ').substring(0, 16)
  const result = db.prepare('INSERT INTO config_files (name, model, version, create_time, status, voltage, current, duty_cycle, pulse_width, channels, sample_rate, voltage_range, waveform, ssid) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)').run(name, model, version, now, status || '生效', voltage || '', current || '', duty_cycle || '', pulse_width || '', channels || 0, sample_rate || '', voltage_range || '', waveform || '', ssid || '')
  return NextResponse.json({ id: result.lastInsertRowid })
}
