import { Injectable } from '@nestjs/common';
import type { WebSocket } from 'ws';

@Injectable()
export class ConsoleSessionService {
  private readonly sessions = new Map<string, Set<WebSocket>>();

  subscribe(serverId: string, socket: WebSocket): void {
    let sockets = this.sessions.get(serverId);
    if (!sockets) {
      sockets = new Set();
      this.sessions.set(serverId, sockets);
    }

    sockets.add(socket);
  }

  unsubscribe(serverId: string, socket: WebSocket): void {
    const sockets = this.sessions.get(serverId);
    if (!sockets) {
      return;
    }

    sockets.delete(socket);
    if (sockets.size === 0) {
      this.sessions.delete(serverId);
    }
  }

  broadcast(serverId: string, line: string): void {
    const sockets = this.sessions.get(serverId);
    if (!sockets) {
      return;
    }

    const payload = JSON.stringify({ type: 'log', line });

    for (const socket of sockets) {
      if (socket.readyState === socket.OPEN) {
        socket.send(payload);
      }
    }
  }
}
