import { Inject, InternalServerErrorException } from '@nestjs/common';
import { type IQueryHandler, QueryHandler } from '@nestjs/cqrs';
import { DomainException, NotFoundException, PrismaService, LoggerService } from '@modules/shared';
import { type LeadReadDto } from '../../../domain/repositories/lead-read.dto';
import { LEAD_REPOSITORY, type ILeadRepository, type PaginatedResult } from '../../../domain/repositories/lead.repository';
import { GetLeadsByAgentQuery } from './get-leads-by-agent.query';

@QueryHandler(GetLeadsByAgentQuery)
export class GetLeadsByAgentHandler implements IQueryHandler<GetLeadsByAgentQuery> {
  constructor(
    @Inject(LEAD_REPOSITORY) private readonly leadRepo: ILeadRepository,
    private readonly prisma: PrismaService,
    private readonly logger: LoggerService,
  ) {}

  async execute(query: GetLeadsByAgentQuery): Promise<PaginatedResult<LeadReadDto>> {
    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.findByAgent(
        agent.id,
        query.status,
        query.page,
        query.limit,
      );
    } catch (error) {
      if (error instanceof DomainException) throw error;
      this.logger.error(
        `Failed to get leads by agent: ${error instanceof Error ? error.message : String(error)}`,
        error instanceof Error ? error.stack : undefined,
        'GetLeadsByAgentHandler',
      );
      throw new InternalServerErrorException('Lỗi khi lấy danh sách lead');
    }
  }
}
