/**
 * GET /api/settings/print-agents  (session) — everything the Printers page needs in one call:
 * { agents:[…], bindings:[…], codes:[…], enabled }
 * agent: { id, name, orgId, online, lastSeen, version, hostname, platform, printers:[…],
 *          queueDepth:{}, health:{}, stats:{queued,sent,spooled,completed,failed}, supportUntil }
 */
import { requireAdminSession } from '../../../utils/printAgentAuth'
import { listAgents, listBindings, listEnrollCodes, isAgentOnline, jobStats, getAgentPrinters, parseJson } from '../../../utils/printSpoolDb'

export default defineEventHandler(async (event) => {
  const session = await requireAdminSession(event)
  const stats = jobStats()
  const agents = listAgents(session.clientId).map(a => ({
    id: a.id,
    name: a.name,
    orgId: a.org_id,
    online: isAgentOnline(a),
    lastSeen: a.last_seen,
    createdAt: a.created_at,
    version: a.version,
    hostname: a.hostname,
    platform: a.platform,
    printers: getAgentPrinters(a),
    queueDepth: parseJson<Record<string, number>>(a.queue_depth_json, {}),
    health: parseJson<any>(a.health_json, null),
    stats: stats[a.id] || {},
    supportUntil: a.support_until,
    allowCupsRelay: Number(a.allow_cups_relay ?? 1) === 1,
    allowSupport: Number(a.allow_support ?? 1) === 1
  }))
  const agentIds = new Set(agents.map(a => a.id))
  const bindings = listBindings().filter(b => agentIds.has(b.agent_id)).map(b => ({
    custPrinterId: b.cust_printer_id, agentId: b.agent_id, cupsName: b.cups_name, orgId: b.org_id, updatedAt: b.updated_at
  }))
  return {
    status: 200,
    enabled: agents.length > 0 || bindings.length > 0,
    agents,
    bindings,
    codes: listEnrollCodes(session.clientId)
  }
})
