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

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

  @OnEvent('user.kyc_updated', { async: true })
  async handle(event: UserKycUpdatedEvent): Promise<void> {
    this.logger.log(`Handling user.kyc_updated for ${event.aggregateId}`, 'UserKycUpdatedListener');

    if (event.newStatus !== 'VERIFIED' && event.newStatus !== 'REJECTED') return;

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

    if (!user?.email) return;

    const templateKey = event.newStatus === 'VERIFIED' ? 'kyc.approved' : 'kyc.rejected';

    await this.commandBus.execute(
      new SendNotificationCommand(
        event.aggregateId,
        'EMAIL',
        templateKey,
        { previousStatus: event.previousStatus, newStatus: event.newStatus },
        user.email,
      ),
    );
  }
}
