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 GuestSubscriber {
  constructor(
    private readonly notificationService: NotificationService,
    private readonly notificationRuleService: NotificationRuleService,
  ) {}

  @OnEvent('guest.invited')
  async handleGuestInvited(payload: any) {
    const { guest } = payload;
    const rules = await this.notificationRuleService.getRulesForEvent(guest.tenantId, 'guest', 'guest.invited');
    for (const rule of rules) {
      for (const channel of rule.channels) {
        await this.notificationService.send(
          channel,
          guest.email || guest.phone || '',
          'Has sido invitado',
          `Hola ${guest.name}, has sido invitado al evento.`,
        );
      }
    }
  }

  @OnEvent('guest.rsvp')
  async handleGuestRsvp(payload: any) {
    const { guest } = payload;
    const rules = await this.notificationRuleService.getRulesForEvent(guest.tenantId, 'guest', 'guest.rsvp');
    for (const rule of rules) {
      for (const channel of rule.channels) {
        await this.notificationService.send(
          channel,
          guest.email || guest.phone || '',
          'RSVP actualizado',
          `Hola ${guest.name}, tu RSVP ha sido actualizado.`,
        );
      }
    }
  }
}
