import 'server-only'
import type { HealthStatus } from '@prisma/client'

// How long a host may go quiet before we stop trusting its last report. The
// agent runs every 5 minutes; three missed runs means something is wrong with
// the host itself, and a stale OK is worse than no OK — a dead VPS reports
// nothing, so silence has to read as a problem rather than as health.
export const STALE_AFTER_SEC = 20 * 60

export const HOST_LABELS: Record<string, string> = {
  'etpics-vps': 'VPS · etpics.com',
  'etminim4': 'Mac mini M4 · SecuritySpy',
  'etminim2': 'Mac mini M2 · Plex',
  'etminim1': 'Mac mini M1',
  // Not a machine: the physical home. The M1's house-watch reports door/window
  // "left open" checks here (separate from etminim1's own job health).
  'house': 'House · doors & sensors',
}

export function hostLabel(host: string): string {
  return HOST_LABELS[host] || host
}

export type Severity = HealthStatus | 'STALE'

export interface CheckView {
  name: string
  label: string
  status: HealthStatus
  value: number | null
  unit: string | null
  detail: string
  since: string
  ageSec: number
  // The agent's raw payload for this check. Persisted since the schema was written
  // ("raw payload, for drilling in") but never surfaced until now — it is what lets a
  // row answer "35 up" with WHICH 35.
  meta?: unknown
}

export interface HostView {
  host: string
  label: string
  status: Severity
  stale: boolean
  reportingAgeSec: number | null
  problems: number
  checks: CheckView[]
}

const RANK: Record<Severity, number> = { OK: 0, WARN: 1, CRIT: 2, STALE: 2 }

export function worst(a: Severity, b: Severity): Severity {
  return RANK[a] >= RANK[b] ? a : b
}
