import { Badge } from '@astryxdesign/core'

/** Structural mirror of collector's `AdapterStatus` (collector/src/state.ts). */
export interface AdapterStalenessStatus {
  id: string
  interval: number
  lastSuccess?: number
  stale: boolean
}

export interface StaleBadgeProps {
  status: AdapterStalenessStatus
  /** Injectable clock for deterministic tests; defaults to Date.now(). */
  now?: number
}

function formatAge(ms: number): string {
  if (ms < 60_000) return `${Math.round(ms / 1000)}s`
  if (ms < 3_600_000) return `${Math.round(ms / 60_000)}m`
  return `${Math.round(ms / 3_600_000)}h`
}

/** Renders nothing unless `status.stale` — the collector's own age > 2×interval verdict. */
export function StaleBadge({ status, now = Date.now() }: StaleBadgeProps) {
  if (!status.stale) return null
  const age = status.lastSuccess === undefined ? null : now - status.lastSuccess
  return <Badge variant="warning" label={`stale${age !== null ? ` · ${formatAge(age)}` : ''}`} />
}