import { Injectable } from '@nestjs/common';
import { CommandBus } from '@nestjs/cqrs';
import { OnEvent } from '@nestjs/event-emitter';
import { type PaymentFailedEvent } from '@modules/payments';
import { LoggerService, PrismaService } from '@modules/shared';
import { SendNotificationCommand } from '../commands/send-notification/send-notification.command';

@Injectable()
export class PaymentFailedListener {
  constructor(
    private readonly commandBus: CommandBus,
    private readonly prisma: PrismaService,
    private readonly logger: LoggerService,
  ) {}

  @OnEvent('payment.failed', { async: true })
  async handle(event: PaymentFailedEvent): Promise<void> {
    this.logger.log(`Handling payment.failed for ${event.aggregateId}`, 'PaymentFailedListener');

    const user = await this.prisma.user.findUnique({
      where: { id: event.userId },
      select: { email: true },
    });

    if (!user?.email) return;

    await this.commandBus.execute(
      new SendNotificationCommand(
        event.userId,
        'EMAIL',
        'payment.failed',
        {
          paymentId: event.aggregateId,
          provider: event.provider,
        },
        user.email,
      ),
    );
  }
}
