import type { DomainEvent, DomainEventType } from './DomainEvent';

type Handler = (event: DomainEvent) => void;

export class EventBus {
  private handlers = new Map<DomainEventType, Handler[]>();

  on(type: DomainEventType, handler: Handler): void {
    if (!this.handlers.has(type)) this.handlers.set(type, []);
    this.handlers.get(type)!.push(handler);
  }

  off(type: DomainEventType, handler: Handler): void {
    const list = this.handlers.get(type);
    if (!list) return;
    const idx = list.indexOf(handler);
    if (idx >= 0) list.splice(idx, 1);
  }

  emit(event: DomainEvent): void {
    const handlers = this.handlers.get(event.type) ?? [];
    for (const h of handlers) h(event);
  }
}
