/**
 * Client-side deduplication manager for WebSocket events.
 * Prevents duplicate message display when the same event is delivered
 * via both WebSocket broadcast and HTTP response.
 *
 * Uses a Set + insertion-order queue for predictable LRU eviction.
 */
export class DedupManager {
  private seen = new Set<string>();
  private order: string[] = [];
  private readonly maxSize: number;

  constructor(maxSize = 5000) {
    this.maxSize = maxSize;
  }

  /** Returns true if this event was already seen (duplicate). */
  checkAndMark(messageId: string, roomId: string): boolean {
    const key = `${roomId}:${messageId}`;
    if (this.seen.has(key)) return true;
    this.seen.add(key);
    this.order.push(key);
    // Evict oldest entries when over limit — remove in batches of 500
    if (this.order.length > this.maxSize) {
      const removeCount = this.order.length - this.maxSize + 500;
      const batch = this.order.splice(0, removeCount);
      for (const k of batch) this.seen.delete(k);
    }
    return false;
  }

  clear(): void {
    this.seen.clear();
    this.order = [];
  }

  destroy(): void {
    this.clear();
  }
}
