import { SSESession } from './sse-mcp-server';

export interface AuthConfig {
  apiKey: string;
  sessionTimeout: number;
  maxAuthAttempts: number;
}

export class AuthHandler {
  private config: AuthConfig;
  private authAttempts: Map<string, number> = new Map();
  private authenticatedSessions: Set<string> = new Set();

  constructor(config: AuthConfig) {
    this.config = config;
  }

  public async authenticate(session: SSESession, apiKey: string): Promise<boolean> {
    // Check if session is already authenticated
    if (this.authenticatedSessions.has(session.id)) {
      return true;
    }

    // Check auth attempts
    const attempts = this.authAttempts.get(session.id) || 0;
    if (attempts >= this.config.maxAuthAttempts) {
      throw new Error('Too many authentication attempts');
    }

    // Validate API key
    if (apiKey !== this.config.apiKey) {
      this.authAttempts.set(session.id, attempts + 1);
      throw new Error('Invalid API key');
    }

    // Authentication successful
    this.authenticatedSessions.add(session.id);
    this.authAttempts.delete(session.id);

    // Set session timeout
    setTimeout(() => {
      this.authenticatedSessions.delete(session.id);
    }, this.config.sessionTimeout);

    return true;
  }

  public isAuthenticated(sessionId: string): boolean {
    return this.authenticatedSessions.has(sessionId);
  }

  public clearSession(sessionId: string): void {
    this.authenticatedSessions.delete(sessionId);
    this.authAttempts.delete(sessionId);
  }
} 