import type { ServerWebSocket } from "bun";
import type { WsData } from "./channel";
import { state } from "./state";

// Broadcast to all connected clients across all channels
export function broadcastToAll(message: object) {
  const data = JSON.stringify(message);
  let clientCount = 0;
  for (const channel of state.channels.values()) {
    for (const ws of channel.clients) {
      ws.send(data);
      clientCount++;
    }
  }
  console.log(`[Broadcast] Sent to ${clientCount} clients`);
}

// Send message to specific user's connections
export function sendToUser(userId: number, message: object) {
  const connections = state.userConnections.get(userId);
  if (connections) {
    const data = JSON.stringify(message);
    for (const ws of connections) {
      ws.send(data);
    }
  }
}

// Broadcast channel list to all clients
export function broadcastChannelList() {
  const list = [...state.channels.values()].map(c => c.getListInfo());
  console.log(`[Broadcast] Sending channel_list to all clients (${list.length} channels)`, JSON.stringify(list.map(c => ({ id: c.id, listeners: c.listeners }))));
  broadcastToAll({ type: "channel_list", channels: list });
}
