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

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

  @OnEvent('user.email_change_requested', { async: true })
  async handle(event: EmailChangeRequestedEvent): Promise<void> {
    this.logger.log(
      `Handling email change OTP for user ${event.aggregateId}`,
      'EmailChangeRequestedListener',
    );

    await this.commandBus.execute(
      new SendNotificationCommand(
        event.aggregateId,
        'EMAIL',
        'user.email_change_otp',
        { otpCode: event.otpCode },
        event.newEmail,
      ),
    );
  }
}
