import {describe, expect, test} from 'bun:test'

import {keyedStaleGuard, staleGuard} from '@/lib/stale-guard'

describe('staleGuard', () => {
  test('the newest claim is current, older ones are stale', () => {
    const guard = staleGuard()
    const first = guard.claim()
    const second = guard.claim()
    expect(guard.isCurrent(first)).toBe(false)
    expect(guard.isCurrent(second)).toBe(true)
  })

  test('invalidate marks every in-flight token stale', () => {
    const guard = staleGuard()
    const token = guard.claim()
    guard.invalidate()
    expect(guard.isCurrent(token)).toBe(false)
  })
})

describe('keyedStaleGuard', () => {
  test("one key's claim never invalidates another's", () => {
    const guard = keyedStaleGuard()
    const a = guard.claim('a')
    const b = guard.claim('b')
    guard.claim('b')
    expect(guard.isCurrent('a', a)).toBe(true)
    expect(guard.isCurrent('b', b)).toBe(false)
  })

  test('invalidate stales every known key without reviving old tokens', () => {
    const guard = keyedStaleGuard()
    const a = guard.claim('a')
    guard.invalidate()
    expect(guard.isCurrent('a', a)).toBe(false)
    // a fresh claim after invalidate must not collide with the stale token
    const next = guard.claim('a')
    expect(next).not.toBe(a)
    expect(guard.isCurrent('a', next)).toBe(true)
  })
})
