import { NextResponse } from 'next/server'
import { db } from '@/lib/db'
import { checkAgentAuth } from '@/lib/agent-auth'
import { hostLabel, STALE_AFTER_SEC } from '@/lib/monitor'

export const runtime = 'nodejs'
export const dynamic = 'force-dynamic'

// GET /api/hosts-health — is every host still reporting?
// Auth: agent bearer token (same as /api/sync and /api/trades-health).
//
// This exists because a host that dies cannot alert about itself. Each host
// emails for its own checks — that is deliberate, so an alert never depends on
// the thing being monitored — but the one thing none of them can report is
// their own silence. The VPS watchdog polls this and mails when a mini goes
// quiet, which is the only alert that genuinely has to live somewhere else.
//
// Deliberately NOT reporting per-check status: each host already emails about
// its own checks, and duplicating that here would mean two emails per fault.
// The single question this answers is "who has stopped talking".
export async function GET(req: Request) {
  if (!checkAgentAuth(req)) {
    return NextResponse.json({ error: 'unauthorized' }, { status: 401 })
  }

  const rows = await db.hostCheck.findMany({ select: { host: true, updatedAt: true } })
  if (!rows.length) {
    return NextResponse.json({ ok: false, reasons: ['no hosts have ever reported'], hosts: [], now: Date.now() })
  }

  const now = Date.now()
  const newest = new Map<string, number>()
  for (const r of rows) {
    const t = r.updatedAt.getTime()
    if (!newest.has(r.host) || t > (newest.get(r.host) as number)) newest.set(r.host, t)
  }

  const hosts = [...newest.entries()].map(([host, t]) => {
    const ageSec = Math.round((now - t) / 1000)
    return { host, label: hostLabel(host), ageSec, stale: ageSec > STALE_AFTER_SEC }
  }).sort((a, b) => b.ageSec - a.ageSec)

  const reasons = hosts.filter(h => h.stale)
    .map(h => `${h.label} has not reported for ${Math.round(h.ageSec / 60)} min (stale after ${Math.round(STALE_AFTER_SEC / 60)} min)`)

  return NextResponse.json({ ok: reasons.length === 0, reasons, hosts, staleAfterSec: STALE_AFTER_SEC, now })
}
