"use strict";

const EventEmitter = require("events");

class SignalEvents extends EventEmitter {
  emitToUser(userId, type, payload = {}) {
    this.emit(`user:${String(userId)}`, {
      type,
      payload,
      timestamp: new Date().toISOString(),
    });
  }

  emitMany(userIds = [], type, payload = {}) {
    const uniqueIds = [...new Set((userIds || []).filter(Boolean).map((x) => String(x)))];
    uniqueIds.forEach((id) => this.emitToUser(id, type, payload));
  }

  subscribe(userId, handler) {
    const room = `user:${String(userId)}`;
    this.on(room, handler);
    return () => this.removeListener(room, handler);
  }
}

module.exports = new SignalEvents();