const cache = new Map<string, { promise: Promise<unknown>; expiresAt: number }>()

const CACHE_TTL_MS = 5000

export function dedup<T>(key: string, fn: () => Promise<T>): Promise<T> {
  const now = Date.now()
  const existing = cache.get(key)

  if (existing && existing.expiresAt > now) {
    return existing.promise as Promise<T>
  }

  const promise = fn()

  cache.set(key, { promise, expiresAt: now + CACHE_TTL_MS })

  promise.finally(() => {
    setTimeout(() => {
      const entry = cache.get(key)
      if (entry && entry.promise === promise) {
        cache.delete(key)
      }
    }, CACHE_TTL_MS)
  })

  return promise
}
