'use strict';

const clients = new Set();

/**
 * Register an SSE response and keep the connection alive.
 */
function addClient(res) {
  res.setHeader('Content-Type', 'text/event-stream');
  res.setHeader('Cache-Control', 'no-cache');
  res.setHeader('Connection', 'keep-alive');
  res.flushHeaders();

  // Send an immediate heartbeat so the browser knows the stream is live
  res.write('data: {"type":"connected"}\n\n');

  const heartbeat = setInterval(() => {
    res.write(': heartbeat\n\n');
  }, 20000);

  clients.add(res);

  res.on('close', () => {
    clearInterval(heartbeat);
    clients.delete(res);
  });
}

/**
 * Push an event to all connected SSE clients.
 */
function broadcast(data) {
  const payload = `data: ${JSON.stringify(data)}\n\n`;
  for (const client of clients) {
    client.write(payload);
  }
}

module.exports = { addClient, broadcast };
