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

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

  @OnEvent('user.phone_change_requested', { async: true })
  async handle(event: PhoneChangeRequestedEvent): Promise<void> {
    this.logger.log(
      `Handling phone change OTP for user ${event.aggregateId}`,
      'PhoneChangeRequestedListener',
    );

    await this.commandBus.execute(
      new SendNotificationCommand(
        event.aggregateId,
        'SMS',
        'user.phone_change_otp',
        { otpCode: event.otpCode },
        event.newPhone,
      ),
    );
  }
}
