import { Inject, InternalServerErrorException } from '@nestjs/common';
import { type IQueryHandler, QueryHandler } from '@nestjs/cqrs';
import { DomainException, NotFoundException, PrismaService, LoggerService } from '@modules/shared';
import { type InquiryReadDto } from '../../../domain/repositories/inquiry-read.dto';
import { INQUIRY_REPOSITORY, type IInquiryRepository, type PaginatedResult } from '../../../domain/repositories/inquiry.repository';
import { GetInquiriesByAgentQuery } from './get-inquiries-by-agent.query';

@QueryHandler(GetInquiriesByAgentQuery)
export class GetInquiriesByAgentHandler implements IQueryHandler<GetInquiriesByAgentQuery> {
  constructor(
    @Inject(INQUIRY_REPOSITORY) private readonly inquiryRepo: IInquiryRepository,
    private readonly prisma: PrismaService,
    private readonly logger: LoggerService,
  ) {}

  async execute(query: GetInquiriesByAgentQuery): Promise<PaginatedResult<InquiryReadDto>> {
    try {
      const agent = await this.prisma.agent.findUnique({
        where: { userId: query.agentUserId },
        select: { id: true },
      });
      if (!agent) {
        throw new NotFoundException('Agent', query.agentUserId);
      }

      return this.inquiryRepo.findByAgent(
        agent.id,
        query.page,
        query.limit,
      );
    } catch (error) {
      if (error instanceof DomainException) throw error;
      this.logger.error(
        `Failed to get inquiries by agent: ${error instanceof Error ? error.message : String(error)}`,
        error instanceof Error ? error.stack : undefined,
        'GetInquiriesByAgentHandler',
      );
      throw new InternalServerErrorException('Lỗi khi lấy danh sách yêu cầu tư vấn');
    }
  }
}
