// src/transport/InMemoryBroker.ts

/**
 * Simple in-memory broker for local transport testing.
 * Connects multiple InMemoryTransport instances together.
 */
export class InMemoryBroker {
  private handlers = new Map<string, Set<(payload: unknown) => void>>();

  subscribe(topic: string, handler: (payload: unknown) => void): () => void {
    let handlers = this.handlers.get(topic);
    if (!handlers) {
      handlers = new Set();
      this.handlers.set(topic, handlers);
    }

    handlers.add(handler);

    return () => {
      const set = this.handlers.get(topic);
      if (set) {
        set.delete(handler);
        if (set.size === 0) {
          this.handlers.delete(topic);
        }
      }
    };
  }

  publish(topic: string, payload: unknown): void {
    const handlers = this.handlers.get(topic);
    if (handlers) {
      for (const handler of handlers) {
        handler(payload);
      }
    }
  }
}
