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

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

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

    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.confirmed',
        {
          paymentId: event.aggregateId,
          amountVND: amountFormatted,
          provider: event.provider,
        },
        user.email,
      ),
    );
  }
}
