import { Inject } from '@nestjs/common';
import { type IQueryHandler, QueryHandler } from '@nestjs/cqrs';
import { NotFoundException, type PrismaService } 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,
  ) {}

  async execute(query: GetInquiriesByAgentQuery): Promise<PaginatedResult<InquiryReadDto>> {
    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,
    );
  }
}
