'use strict';
// Server-Sent Events hub — werkt onder zowel Node als de Bun-standalone (gewoon HTTP).
// Vervangt de WebSocket-laag: server → browser via een open SSE-stream, browser → server
// via POST /api/cmd.
function createSSE() {
  const clients = new Set();

  function add(req, res) {
    res.writeHead(200, {
      'Content-Type': 'text/event-stream; charset=utf-8',
      'Cache-Control': 'no-cache, no-transform',
      'Connection': 'keep-alive',
      'X-Accel-Buffering': 'no',
    });
    res.write(': verbonden\n\n');
    clients.add(res);
    req.on('close', () => { clients.delete(res); });
  }

  function sendTo(res, str) {
    try { res.write('data: ' + str.replace(/\n/g, '\\n') + '\n\n'); } catch (_) { clients.delete(res); }
  }
  function broadcast(str) { for (const res of clients) sendTo(res, str); }

  // keepalive (comment-regel) zodat de verbinding open blijft
  setInterval(() => { for (const res of clients) { try { res.write(': ping\n\n'); } catch (_) { clients.delete(res); } } }, 20000).unref();

  return { add, sendTo, broadcast, get size() { return clients.size; } };
}

module.exports = { createSSE };
