/**
 * EventEmitter - Typsicherer Event-Handler
 */

type EventCallback<T = unknown> = (data: T) => void;

// eslint-disable-next-line @typescript-eslint/no-explicit-any
export class EventEmitter<Events extends Record<string, any> = Record<string, unknown>> {
  private listeners: Map<keyof Events, Set<EventCallback<unknown>>> = new Map();

  /**
   * Event-Listener registrieren
   * @returns Unsubscribe-Funktion
   */
  on<K extends keyof Events>(
    event: K,
    callback: EventCallback<Events[K]>
  ): () => void {
    if (!this.listeners.has(event)) {
      this.listeners.set(event, new Set());
    }

    this.listeners.get(event)!.add(callback as EventCallback<unknown>);

    // Unsubscribe-Funktion zurueckgeben
    return () => this.off(event, callback);
  }

  /**
   * Event-Listener entfernen
   */
  off<K extends keyof Events>(
    event: K,
    callback: EventCallback<Events[K]>
  ): void {
    this.listeners.get(event)?.delete(callback as EventCallback<unknown>);
  }

  /**
   * Event emittieren
   */
  emit<K extends keyof Events>(event: K, data: Events[K]): void {
    this.listeners.get(event)?.forEach((callback) => {
      try {
        callback(data);
      } catch (error) {
        console.error(`Error in event handler for ${String(event)}:`, error);
      }
    });
  }

  /**
   * Einmaligen Listener registrieren
   */
  once<K extends keyof Events>(
    event: K,
    callback: EventCallback<Events[K]>
  ): () => void {
    const wrapper = (data: Events[K]) => {
      this.off(event, wrapper);
      callback(data);
    };

    return this.on(event, wrapper);
  }

  /**
   * Alle Listener entfernen
   */
  clear(): void {
    this.listeners.clear();
  }

  /**
   * Alle Listener fuer ein Event entfernen
   */
  clearEvent<K extends keyof Events>(event: K): void {
    this.listeners.delete(event);
  }

  /**
   * Anzahl Listener fuer ein Event
   */
  listenerCount<K extends keyof Events>(event: K): number {
    return this.listeners.get(event)?.size ?? 0;
  }
}

export default EventEmitter;
