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

  async execute(query: GetMarketReportQuery): Promise<MarketReportDto> {
    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',
    );
  }
}
