import { Inject, InternalServerErrorException } from '@nestjs/common';
import { type IQueryHandler, QueryHandler } from '@nestjs/cqrs';
import { DomainException, NotFoundException, PrismaService, LoggerService } 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,
    private readonly logger: LoggerService,
  ) {}

  async execute(query: GetLeadStatsQuery): Promise<LeadStatsData> {
    try {
      // 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);
    } catch (error) {
      if (error instanceof DomainException) throw error;
      this.logger.error(
        `Failed to get lead stats: ${error instanceof Error ? error.message : String(error)}`,
        error instanceof Error ? error.stack : undefined,
        'GetLeadStatsHandler',
      );
      throw new InternalServerErrorException('Lỗi khi lấy thống kê lead');
    }
  }
}
