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

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

  @OnEvent('user.password_reset_requested', { async: true })
  async handle(event: PasswordResetRequestedEvent): Promise<void> {
    this.logger.log(
      `Handling password reset OTP for user ${event.aggregateId}`,
      'PasswordResetRequestedListener',
    );

    await this.commandBus.execute(
      new SendNotificationCommand(
        event.aggregateId,
        'EMAIL',
        'password.reset',
        { otp: event.otpCode, expiryMinutes: 15 },
        event.email,
      ),
    );
  }
}
