import type { ScreenPoller } from './screen-poller.js';

interface ClientSession {
  id: string;
  authenticated: boolean;
  subscriptions: Set<string>; // "workspace:surface" keys
}

export class SessionManager {
  private sessions = new Map<string, ClientSession>();
  private poller: ScreenPoller;

  constructor(poller: ScreenPoller) {
    this.poller = poller;
  }

  addClient(clientId: string): void {
    this.sessions.set(clientId, {
      id: clientId,
      authenticated: false,
      subscriptions: new Set(),
    });
  }

  authenticateClient(clientId: string): void {
    const session = this.sessions.get(clientId);
    if (session) session.authenticated = true;
  }

  isAuthenticated(clientId: string): boolean {
    return this.sessions.get(clientId)?.authenticated ?? false;
  }

  subscribe(clientId: string, workspace: string, surface: string): void {
    const session = this.sessions.get(clientId);
    if (!session) return;

    const key = `${workspace}:${surface}`;
    session.subscriptions.add(key);
    this.poller.subscribe(clientId, workspace, surface);
  }

  unsubscribe(clientId: string, surface: string): void {
    const session = this.sessions.get(clientId);
    if (!session) return;

    for (const key of session.subscriptions) {
      if (key.endsWith(`:${surface}`)) {
        session.subscriptions.delete(key);
      }
    }
    this.poller.unsubscribe(clientId, surface);
  }

  removeClient(clientId: string): void {
    const session = this.sessions.get(clientId);
    if (!session) return;

    // Unsubscribe from all surfaces
    this.poller.unsubscribe(clientId);
    this.sessions.delete(clientId);
  }

  getSubscribedClients(surface: string): string[] {
    const clients: string[] = [];
    for (const [id, session] of this.sessions) {
      for (const key of session.subscriptions) {
        if (key.endsWith(`:${surface}`)) {
          clients.push(id);
          break;
        }
      }
    }
    return clients;
  }

  getClientCount(): number {
    return this.sessions.size;
  }

  getAuthenticatedCount(): number {
    let count = 0;
    for (const session of this.sessions.values()) {
      if (session.authenticated) count++;
    }
    return count;
  }
}
