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

export async function GET() {
  seedIfEmpty()
  const db = getDb()

  const q = (sql: string) => (db.prepare(sql).get() as { c: number }).c

  const devices = {
    total: q('SELECT COUNT(*) as c FROM devices'),
    assembling: q("SELECT COUNT(*) as c FROM devices WHERE status = '装配中'"),
    activated: q("SELECT COUNT(*) as c FROM devices WHERE status = '已激活'"),
    shipped: q("SELECT COUNT(*) as c FROM devices WHERE status = '已出厂'"),
  }

  const materials = {
    total: q('SELECT COUNT(*) as c FROM materials'),
    inStock: q("SELECT COUNT(*) as c FROM materials WHERE status = '在库'"),
    assembled: q("SELECT COUNT(*) as c FROM materials WHERE status = '已装配'"),
    faulty: q("SELECT COUNT(*) as c FROM materials WHERE status = '故障'"),
  }

  const repair = {
    total: q('SELECT COUNT(*) as c FROM repair_orders'),
    pending: q("SELECT COUNT(*) as c FROM repair_orders WHERE status = '待处理'"),
    processing: q("SELECT COUNT(*) as c FROM repair_orders WHERE status = '处理中'"),
    done: q("SELECT COUNT(*) as c FROM repair_orders WHERE status = '已处理'"),
  }

  const scrap = {
    total: q('SELECT COUNT(*) as c FROM scrap_records'),
    pendingApproval: q("SELECT COUNT(*) as c FROM scrap_records WHERE status = '待审批'"),
  }

  const firmware = { total: q('SELECT COUNT(*) as c FROM firmware') }
  const licenses = { total: q('SELECT COUNT(*) as c FROM licenses') }

  // Recent pending repair orders
  const recentRepairs = db.prepare("SELECT id, sn, fault_type, status, priority, create_date FROM repair_orders WHERE status != '已处理' ORDER BY create_date DESC LIMIT 4").all()

  // Recent scrap pending approval
  const recentScraps = db.prepare("SELECT id, sn, model, status, date FROM scrap_records WHERE status = '待审批' OR status = '审批中' ORDER BY date DESC LIMIT 4").all()

  return NextResponse.json({ devices, materials, repair, scrap, firmware, licenses, recentRepairs, recentScraps })
}
