// WebSocket bridge to connect HTTP API routes with the WebSocket server in server.js
// This provides a way to broadcast messages from API routes

interface WebSocketMessage {
  type: string;
  [key: string]: any;
}

// Global WebSocket connections - populated by server.js
declare global {
  var wsConnections: Map<string, any> | undefined;
  var wsUserConnections: Map<string, string> | undefined;
  var wsRoomConnections: Map<string, Set<string>> | undefined;
}

export class WebSocketBridge {
  private static instance: WebSocketBridge;

  static getInstance(): WebSocketBridge {
    if (!WebSocketBridge.instance) {
      WebSocketBridge.instance = new WebSocketBridge();
    }
    return WebSocketBridge.instance;
  }

  sendToUser(userId: string, message: WebSocketMessage): boolean {
    try {
      if (typeof window !== 'undefined') return false; // Client-side only
      
      const userConnections = global.wsUserConnections;
      const connections = global.wsConnections;
      
      if (!userConnections || !connections) {
        return false;
      }

      const connectionId = userConnections.get(userId);
      if (!connectionId) {
        return false;
      }

      const ws = connections.get(connectionId);
      if (!ws) {
        return false;
      }

      if (ws.readyState === 1) { // WebSocket.OPEN
        ws.send(JSON.stringify(message));
        return true;
      } else {
        return false;
      }
    } catch (error) {
      return false;
    }
  }

  broadcastToRoom(roomId: string, message: WebSocketMessage, excludeConnectionId?: string): number {
    try {
      if (typeof window !== 'undefined') return 0; // Server-side only
      
      const roomConnections = global.wsRoomConnections;
      const connections = global.wsConnections;
      
      if (!roomConnections || !connections) {
        return 0;
      }

      const roomConns = roomConnections.get(roomId);
      if (!roomConns) {
        return 0;
      }

      let sentCount = 0;
      roomConns.forEach(connectionId => {
        if (connectionId !== excludeConnectionId) {
          const ws = connections.get(connectionId);
          if (ws && ws.readyState === 1) { // WebSocket.OPEN
            try {
              ws.send(JSON.stringify(message));
              sentCount++;
            } catch (error) {
            }
          }
        }
      });

      return sentCount;
    } catch (error) {
      return 0;
    }
  }

  getConnectedUsers(): string[] {
    try {
      if (typeof window !== 'undefined') return []; // Server-side only
      
      const userConnections = global.wsUserConnections;
      if (!userConnections) return [];
      
      return Array.from(userConnections.keys());
    } catch (error) {
      return [];
    }
  }

  isUserConnected(userId: string): boolean {
    try {
      if (typeof window !== 'undefined') return false; // Server-side only
      
      const userConnections = global.wsUserConnections;
      if (!userConnections) return false;
      
      return userConnections.has(userId);
    } catch (error) {
      return false;
    }
  }
}

// Export singleton instance
export const wsBridge = WebSocketBridge.getInstance();
