const DEFAULT_OFFLINE_THRESHOLD_MS = 10 * 60 * 1000
const DEFAULT_STALE_THRESHOLD_MS = DEFAULT_OFFLINE_THRESHOLD_MS * 12

function parseThreshold(raw: string | undefined, fallback: number) {
  if (!raw) return fallback
  const parsed = Number(raw)
  if (!Number.isFinite(parsed) || parsed <= 0) return fallback
  return parsed
}

const MACHINE_OFFLINE_THRESHOLD_MS = parseThreshold(
  process.env.NEXT_PUBLIC_MACHINE_OFFLINE_THRESHOLD_MS,
  DEFAULT_OFFLINE_THRESHOLD_MS
)
const MACHINE_STALE_THRESHOLD_MS = parseThreshold(
  process.env.NEXT_PUBLIC_MACHINE_STALE_THRESHOLD_MS,
  DEFAULT_STALE_THRESHOLD_MS
)

export const DEVICE_STATUS_LABELS: Record<string, string> = {
  online: "Online",
  offline: "Offline",
  stale: "Sem sinal",
  maintenance: "Em manutenção",
  blocked: "Bloqueado",
  deactivated: "Desativado",
  unknown: "Desconhecida",
}

export type DeviceStatusSource = {
  status?: string | null
  lastHeartbeatAt?: number | null
  isActive?: boolean | null
}

export function resolveDeviceStatus(source?: DeviceStatusSource | null): string {
  if (!source) return "unknown"
  if (source.isActive === false) return "deactivated"
  const manualStatus = (source.status ?? "").toLowerCase()
  if (manualStatus === "maintenance" || manualStatus === "blocked") {
    return manualStatus
  }
  const heartbeat = source.lastHeartbeatAt
  if (typeof heartbeat === "number" && Number.isFinite(heartbeat) && heartbeat > 0) {
    const age = Date.now() - heartbeat
    if (age <= MACHINE_OFFLINE_THRESHOLD_MS) return "online"
    if (age <= MACHINE_STALE_THRESHOLD_MS) return "offline"
    return "stale"
  }
  return source.status ?? "unknown"
}

const STATUS_INDICATORS: Record<
  string,
  { dotClass: string; ringClass: string; isPinging: boolean }
> = {
  online: { dotClass: "bg-emerald-500", ringClass: "bg-emerald-400/30", isPinging: true },
  offline: { dotClass: "bg-rose-500", ringClass: "bg-rose-400/30", isPinging: false },
  stale: { dotClass: "bg-amber-500", ringClass: "bg-amber-400/30", isPinging: false },
  maintenance: { dotClass: "bg-amber-500", ringClass: "bg-amber-400/30", isPinging: false },
  blocked: { dotClass: "bg-orange-500", ringClass: "bg-orange-400/30", isPinging: false },
  deactivated: { dotClass: "bg-slate-500", ringClass: "bg-slate-400/40", isPinging: false },
  unknown: { dotClass: "bg-slate-400", ringClass: "bg-slate-300/30", isPinging: false },
}

export function getDeviceStatusIndicator(status?: string | null) {
  const normalized = (status ?? "unknown").toLowerCase()
  return STATUS_INDICATORS[normalized] ?? STATUS_INDICATORS.unknown
}
