import { describe, expect, it } from 'vitest'
import type { AdapterStatus, Panel } from './collector-types'
import { panelFreshness } from './panel-freshness'

const NOW = Date.parse('2026-08-03T13:00:00.000Z')

function panel(ts: string): Panel {
  return { id: 'plans', ts, data: {} }
}

function adapter(overrides: Partial<AdapterStatus> = {}): AdapterStatus {
  return { id: 'harness', interval: 30_000, consecutiveErrors: 0, stale: false, ...overrides }
}

describe('panelFreshness', () => {
  it('reports a payload the browser stopped refreshing as stale', () => {
    const status = panelFreshness(panel('2026-08-03T12:55:00.000Z'), adapter(), NOW)

    expect(status).toMatchObject({ stale: true, lastSuccess: Date.parse('2026-08-03T12:55:00.000Z') })
  })

  it('stays quiet while the payload is within two poll intervals', () => {
    expect(panelFreshness(panel('2026-08-03T12:59:45.000Z'), adapter(), NOW)?.stale).toBe(false)
  })

  it('keeps the collector own stale verdict even on a fresh payload', () => {
    expect(panelFreshness(panel('2026-08-03T13:00:00.000Z'), adapter({ stale: true }), NOW)?.stale).toBe(true)
  })

  it('falls back to the adapter when the panel carries no usable stamp', () => {
    const upstream = adapter({ stale: true })

    expect(panelFreshness(panel('not-a-date'), upstream, NOW)).toBe(upstream)
    expect(panelFreshness(undefined, upstream, NOW)).toBe(upstream)
  })
})
