import { Injectable, Logger } from '@nestjs/common';
import { OnEvent } from '@nestjs/event-emitter';
import { type NotifyPayload } from './notification.constants';
import { NotificationService } from './notification.service';

/**
 * Subscribes to the 'notify' domain event. The money/business services just emit
 * (they don't know NotificationService exists — loose coupling); this listener
 * is the only bridge. Async + promisify so an awaited emitAsync completes the
 * dispatch, keeping it deterministic and testable.
 */
@Injectable()
export class NotificationListener {
  private readonly logger = new Logger('NotificationListener');

  constructor(private readonly notifications: NotificationService) {}

  @OnEvent('notify', { async: true, promisify: true })
  async handle(payload: NotifyPayload): Promise<void> {
    try {
      await this.notifications.dispatch(payload);
    } catch (err) {
      this.logger.error(`notify handler error: ${err instanceof Error ? err.message : err}`);
    }
  }
}
