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

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

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

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

    if (!user) return;

    // Send welcome email if user has email
    if (user.email) {
      await this.commandBus.execute(
        new SendNotificationCommand(
          event.aggregateId,
          'EMAIL',
          'user.registered',
          { phone: event.phone, role: event.role },
          user.email,
        ),
      );
    }
  }
}
