import 'server-only';
import { EventEmitter } from 'node:events';

// Single in-process pub/sub for real-time inbox updates (one Node server in dev / single instance).
const g = globalThis as unknown as { __dkBus?: EventEmitter };

function make(): EventEmitter {
  const e = new EventEmitter();
  e.setMaxListeners(0); // many concurrent SSE subscribers
  return e;
}

export const bus: EventEmitter = g.__dkBus ?? (g.__dkBus = make());

const chan = (userId: number) => `inbox:${userId}`;

/** Notify a user's open SSE streams that their inbox changed. */
export function notifyInbox(userId: number): void {
  bus.emit(chan(userId));
}

export function subscribeInbox(userId: number, cb: () => void): () => void {
  const c = chan(userId);
  bus.on(c, cb);
  return () => bus.off(c, cb);
}
