import type { AdapterStalenessStatus } from '@overdeck/deck-ui'
import type { AdapterStatus, Panel } from './collector-types'

const DEFAULT_INTERVAL_MS = 30_000

/**
 * Staleness as the browser can actually observe it. The collector's own `stale` flag
 * only reports whether *it* is polling upstream — it says nothing about a deck whose
 * cache stopped updating, which is the case that renders finished runs as `running`.
 * Panel `ts` is stamped server-side on each successful poll, so its age measures the
 * whole path, collector included.
 */
export function panelFreshness(
  panel: Panel | undefined,
  adapter: AdapterStatus | undefined,
  now: number = Date.now(),
): AdapterStalenessStatus | undefined {
  const interval = adapter?.interval ?? DEFAULT_INTERVAL_MS
  const stampedAt = panel ? Date.parse(panel.ts) : Number.NaN
  if (!Number.isFinite(stampedAt)) return adapter

  return {
    id: panel?.id ?? adapter?.id ?? 'panel',
    interval,
    lastSuccess: stampedAt,
    stale: (adapter?.stale ?? false) || now - stampedAt > interval * 2,
  }
}
