import { Inject, InternalServerErrorException } from '@nestjs/common';
import { type IQueryHandler, QueryHandler } from '@nestjs/cqrs';
import { DomainException, 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 { GetInquiriesByListingQuery } from './get-inquiries-by-listing.query';

@QueryHandler(GetInquiriesByListingQuery)
export class GetInquiriesByListingHandler implements IQueryHandler<GetInquiriesByListingQuery> {
  constructor(
    @Inject(INQUIRY_REPOSITORY) private readonly inquiryRepo: IInquiryRepository,
    private readonly logger: LoggerService,
  ) {}

  async execute(query: GetInquiriesByListingQuery): Promise<PaginatedResult<InquiryReadDto>> {
    try {
      return await this.inquiryRepo.findByListing(
        query.listingId,
        query.page,
        query.limit,
      );
    } catch (error) {
      if (error instanceof DomainException) throw error;
      this.logger.error(
        `Failed to get inquiries by listing: ${error instanceof Error ? error.message : String(error)}`,
        error instanceof Error ? error.stack : undefined,
        'GetInquiriesByListingHandler',
      );
      throw new InternalServerErrorException('Lỗi khi lấy danh sách yêu cầu tư vấn');
    }
  }
}
