// Server-Sent Events broadcast utility

type SSEClient = {
  id: string;
  controller: ReadableStreamDefaultController;
};

const clients: SSEClient[] = [];

export function addClient(controller: ReadableStreamDefaultController): string {
  const id = Math.random().toString(36).slice(2);
  clients.push({ id, controller });
  return id;
}

export function removeClient(id: string) {
  const idx = clients.findIndex(c => c.id === id);
  if (idx !== -1) clients.splice(idx, 1);
}

export function broadcast(event: string, data: unknown) {
  const payload = `event: ${event}\ndata: ${JSON.stringify(data)}\n\n`;
  const encoder = new TextEncoder();
  const bytes = encoder.encode(payload);

  for (const client of clients) {
    try {
      client.controller.enqueue(bytes);
    } catch {
      // Client disconnected, will be cleaned up
    }
  }
}
