import { Injectable } from '@nestjs/common';
import { EventEmitter2 } from '@nestjs/event-emitter';

@Injectable()
export class EventsService {
  constructor(readonly event: EventEmitter2) {}

  public async waitForEvent<T>(
    eventName: string,
    timeoutMs = 10000,
  ): Promise<T> {
    return new Promise((resolve, reject) => {
      const timer = setTimeout(() => {
        this.event.off(eventName, listener); // cleanup
        reject(null); // hoặc reject(new Error('Timeout')) nếu muốn
      }, timeoutMs);

      const listener = (data: any) => {
        clearTimeout(timer);
        this.event.off(eventName, listener); // cleanup
        resolve(data);
      };

      this.event.on(eventName, listener);
    });
  }

  public async sendEvent<T>(eventName: string, data: T) {
    return this.event.emit(eventName, data);
  }
}
