import EventEmitter from 'events';
import { DomainEvent, IDomainEventPublisher } from '../../application/ports/domain-event-publisher';

/**
 * In-memory implementation of the domain event publisher.
 *
 * This is intentionally lightweight: it runs inside the application process and
 * routes events to registered handlers. It is the infrastructure's responsibility
 * to choose a different transport (Redis, RabbitMQ, etc.) if the system needs to
 * scale beyond a single process, without changing the application interface.
 */
export class InMemoryDomainEventPublisher implements IDomainEventPublisher {
  private readonly emitter = new EventEmitter();

  publish<T extends DomainEvent>(event: T): void {
    this.emitter.emit(event.type, event);
  }

  subscribe<T extends DomainEvent>(
    eventType: T['type'],
    handler: (event: T) => void | Promise<void>,
  ): void {
    this.emitter.on(eventType, handler);
  }
}
