import { Inject } from '@nestjs/common';
import { type IQueryHandler, QueryHandler } from '@nestjs/cqrs';
import { NotFoundException, type PrismaService } from '@modules/shared';
import { LEAD_REPOSITORY, type ILeadRepository, type LeadStatsData } from '../../../domain/repositories/lead.repository';
import { GetLeadStatsQuery } from './get-lead-stats.query';

@QueryHandler(GetLeadStatsQuery)
export class GetLeadStatsHandler implements IQueryHandler<GetLeadStatsQuery> {
  constructor(
    @Inject(LEAD_REPOSITORY) private readonly leadRepo: ILeadRepository,
    private readonly prisma: PrismaService,
  ) {}

  async execute(query: GetLeadStatsQuery): Promise<LeadStatsData> {
    // Look up agent by userId
    const agent = await this.prisma.agent.findUnique({
      where: { userId: query.agentUserId },
    });
    if (!agent) {
      throw new NotFoundException('Agent', query.agentUserId);
    }

    return this.leadRepo.getStatsByAgent(agent.id);
  }
}
