import { OnEvent } from '@nestjs/event-emitter';
import { Injectable } from '@nestjs/common';
import { NotificationService } from '../../core/services/notification.service';
import { NotificationRuleService } from '../../core/services/notification-rule.service';

@Injectable()
export class GiftSubscriber {
  constructor(
    private readonly notificationService: NotificationService,
    private readonly notificationRuleService: NotificationRuleService,
  ) {}

  @OnEvent('gift.created')
  async handleGiftCreated(payload: any) {
    const { gift } = payload;
    const rules = await this.notificationRuleService.getRulesForEvent(gift.tenantId, 'gift', 'gift.created');
    for (const rule of rules) {
      for (const channel of rule.channels) {
        await this.notificationService.send(
          channel,
          gift.metadata?.notifyTo || '',
          'Nuevo regalo creado',
          `Se ha creado el regalo: ${gift.name}`,
        );
      }
    }
  }

  @OnEvent('gift.contribution')
  async handleGiftContribution(payload: any) {
    const { contribution } = payload;
    const rules = await this.notificationRuleService.getRulesForEvent(contribution.tenantId, 'gift', 'gift.contribution');
    for (const rule of rules) {
      for (const channel of rule.channels) {
        await this.notificationService.send(
          channel,
          contribution.metadata?.notifyTo || '',
          'Nuevo aporte a regalo',
          `Se ha registrado un aporte de ${contribution.amount} al regalo (${contribution.giftId}).`,
        );
      }
    }
  }
}
