import { Injectable } from "@nestjs/common";
import { ConfigService } from "@nestjs/config";

/**
 * Simple per-instance SSE connection limiter.
 *
 * This prevents a single user (or a runaway client) from opening an unbounded number of
 * long-lived SSE connections to a single BFF instance.
 *
 * Note: This is intentionally in-memory (fast, low overhead). RateLimitGuard still protects
 * connection attempts globally (Redis-backed) across instances.
 */
@Injectable()
export class RealtimeConnectionLimiterService {
  private readonly maxPerUser: number;
  private readonly counts = new Map<string, number>();

  constructor(config: ConfigService) {
    this.maxPerUser = config.get<number>("REALTIME_MAX_CONNECTIONS_PER_USER", 3);
  }

  tryAcquire(userId: string): boolean {
    const current = this.counts.get(userId) ?? 0;
    if (current >= this.maxPerUser) {
      return false;
    }
    this.counts.set(userId, current + 1);
    return true;
  }

  release(userId: string): void {
    const current = this.counts.get(userId) ?? 0;
    if (current <= 1) {
      this.counts.delete(userId);
      return;
    }
    this.counts.set(userId, current - 1);
  }
}
