import { Inject, InternalServerErrorException } from '@nestjs/common';
import { QueryHandler, type IQueryHandler } from '@nestjs/cqrs';
import { DomainException, CacheService, CachePrefix, CacheTTL, LoggerService } from '@modules/shared';
import {
  MARKET_INDEX_REPOSITORY,
  type IMarketIndexRepository,
  type MarketReportResult,
} from '../../../domain/repositories/market-index.repository';
import { GetMarketReportQuery } from './get-market-report.query';

export interface MarketReportDto {
  city: string;
  period: string;
  districts: MarketReportResult[];
}

@QueryHandler(GetMarketReportQuery)
export class GetMarketReportHandler implements IQueryHandler<GetMarketReportQuery> {
  constructor(
    @Inject(MARKET_INDEX_REPOSITORY) private readonly marketIndexRepo: IMarketIndexRepository,
    private readonly cache: CacheService,
    private readonly logger: LoggerService,
  ) {}

  async execute(query: GetMarketReportQuery): Promise<MarketReportDto> {
    try {
      const cacheKey = CacheService.buildKey(CachePrefix.MARKET_REPORT, query.city, query.period, query.propertyType);

      return this.cache.getOrSet(
        cacheKey,
        async () => {
          const districts = await this.marketIndexRepo.getMarketReport(
            query.city,
            query.period,
            query.propertyType,
          );
          return { city: query.city, period: query.period, districts };
        },
        CacheTTL.MARKET_REPORT,
        'market_report',
      );
    } catch (error) {
      if (error instanceof DomainException) throw error;
      this.logger.error(
        `Failed to truy vấn báo cáo thị trường: ${error instanceof Error ? error.message : error}`,
        error instanceof Error ? error.stack : undefined,
        this.constructor.name,
      );
      throw new InternalServerErrorException('Không thể truy vấn báo cáo thị trường. Vui lòng thử lại sau.');
    }
  }
}
