import assert from 'node:assert/strict'
import test from 'node:test'

import { WorkerListCache } from './worker-list-cache.js'

test('WorkerListCache coalesces concurrent reads and expires entries', async () => {
  const cache = new WorkerListCache(15)
  let calls = 0
  const factory = async () => {
    calls += 1
    await new Promise((resolve) => setTimeout(resolve, 1))
    return { calls }
  }

  const [first, second] = await Promise.all([
    cache.getOrSet('same', factory),
    cache.getOrSet('same', factory),
  ])
  assert.deepEqual(first, { calls: 1 })
  assert.deepEqual(second, { calls: 1 })
  assert.equal(calls, 1)

  await new Promise((resolve) => setTimeout(resolve, 20))
  assert.deepEqual(await cache.getOrSet('same', factory), { calls: 2 })
  assert.equal(calls, 2)
})
