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

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

  @OnEvent('agent.verified', { async: true })
  async handle(event: AgentVerifiedEvent): Promise<void> {
    this.logger.log(`Handling agent.verified for ${event.aggregateId}`, 'AgentVerifiedListener');

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

    if (!agent?.user.email) return;

    await this.commandBus.execute(
      new SendNotificationCommand(
        agent.user.id,
        'EMAIL',
        'agent.verified',
        { agentId: event.aggregateId },
        agent.user.email,
      ),
    );
  }
}
