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

export async function GET(req: NextRequest) {
  seedIfEmpty()
  const db = getDb()
  const board = req.nextUrl.searchParams.get('board') || ''
  const model = req.nextUrl.searchParams.get('model') || ''
  let items
  if (board) {
    items = db.prepare('SELECT * FROM firmware WHERE board_version = ? ORDER BY date DESC').all(board)
  } else if (model) {
    items = db.prepare('SELECT * FROM firmware WHERE model_code = ? ORDER BY date DESC').all(model)
  } else {
    const type = req.nextUrl.searchParams.get('type') || ''
    if (type) {
      items = db.prepare('SELECT * FROM firmware WHERE type = ? ORDER BY date DESC').all(type)
    } else {
      items = db.prepare('SELECT * FROM firmware ORDER BY date DESC').all()
    }
  }
  const parsed = (items as { notes: string; [k: string]: unknown }[]).map(i => ({ ...i, notes: JSON.parse(i.notes as string) }))
  return NextResponse.json(parsed)
}

export async function POST(req: Request) {
  seedIfEmpty()
  const db = getDb()
  const body = await req.json()
  const { version, board_version, type, date, status, size, hw_range, upgrade_type, signed, notes, model_code } = body
  const result = db.prepare("INSERT INTO firmware (version, board_version, type, date, status, size, downloads, hw_range, upgrade_type, signed, md5, sha256, notes, model_code) VALUES (?, ?, ?, ?, ?, ?, 0, ?, ?, ?, '', '', ?, ?)").run(version, board_version || '-', type, date || new Date().toISOString().split('T')[0], status || '草稿', size || '', hw_range || '', upgrade_type || '可选', signed ? 1 : 0, JSON.stringify(notes || []), model_code || '')
  return NextResponse.json({ id: result.lastInsertRowid })
}
