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

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

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

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

    if (!user?.email) return;

    const amountFormatted = new Intl.NumberFormat('vi-VN').format(event.amountVND);

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