import type { SendResponse } from '@zyphon/shared-types';

interface CachedEntry {
  response: SendResponse;
  expiresAt: number;
}

export class IdempotencyManager {
  private cache = new Map<string, CachedEntry>();
  private readonly ttlMs: number;
  private readonly maxEntries: number;

  constructor(ttlMinutes = 5, maxEntries = 5000) {
    this.ttlMs = ttlMinutes * 60 * 1000;
    this.maxEntries = maxEntries;
  }

  public get(key: string): SendResponse | null {
    const entry = this.cache.get(key);
    if (!entry) return null;

    if (Date.now() > entry.expiresAt) {
      this.cache.delete(key);
      return null;
    }

    return entry.response;
  }

  public set(key: string, response: SendResponse): void {
    if (this.cache.size >= this.maxEntries) {
      // Evict oldest entry (Map maintains insertion order)
      const oldestKey = this.cache.keys().next().value;
      if (oldestKey) this.cache.delete(oldestKey);
    }

    this.cache.set(key, {
      response,
      expiresAt: Date.now() + this.ttlMs,
    });
  }

  public clear(): void {
    this.cache.clear();
  }
}

