/**
 * SSE Manager – verwaltet offene EventSource-Verbindungen pro Ticket.
 * clients: Map<ticketId (number), Set<{ res, canSeeInternal }>>
 */

const clients = new Map();

function subscribe(ticketId, res, canSeeInternal) {
    if (!clients.has(ticketId)) clients.set(ticketId, new Set());
    clients.get(ticketId).add({ res, canSeeInternal });
}

function unsubscribe(ticketId, res) {
    const set = clients.get(ticketId);
    if (!set) return;
    for (const client of set) {
        if (client.res === res) { set.delete(client); break; }
    }
    if (set.size === 0) clients.delete(ticketId);
}

/**
 * Schickt einen neuen Kommentar an alle Clients des Tickets.
 * Interne Kommentare werden nur an Support/Admin-Clients geschickt.
 */
function broadcast(ticketId, comment) {
    const set = clients.get(ticketId);
    if (!set || set.size === 0) return;

    for (const client of set) {
        if (comment.is_internal && !client.canSeeInternal) continue;
        try {
            client.res.write(`event: comment\ndata: ${JSON.stringify(comment)}\n\n`);
        } catch (_) {
            // Client already disconnected
        }
    }
}

module.exports = { subscribe, unsubscribe, broadcast };
