import { Inject } from '@nestjs/common';
import { QueryHandler, type IQueryHandler } from '@nestjs/cqrs';
import { CacheService, CachePrefix, CacheTTL } from '@modules/shared/infrastructure/cache.service';
import {
  MARKET_INDEX_REPOSITORY,
  type IMarketIndexRepository,
  type PriceTrendPoint,
} from '../../../domain/repositories/market-index.repository';
import { GetPriceTrendQuery } from './get-price-trend.query';

export interface PriceTrendDto {
  district: string;
  city: string;
  propertyType: string;
  trend: PriceTrendPoint[];
}

@QueryHandler(GetPriceTrendQuery)
export class GetPriceTrendHandler implements IQueryHandler<GetPriceTrendQuery> {
  constructor(
    @Inject(MARKET_INDEX_REPOSITORY) private readonly marketIndexRepo: IMarketIndexRepository,
    private readonly cache: CacheService,
  ) {}

  async execute(query: GetPriceTrendQuery): Promise<PriceTrendDto> {
    const cacheKey = CacheService.buildKey(
      CachePrefix.MARKET_TREND,
      query.district,
      query.city,
      query.propertyType,
      query.periods?.join(','),
    );

    return this.cache.getOrSet(
      cacheKey,
      async () => {
        const trend = await this.marketIndexRepo.getPriceTrend(
          query.district,
          query.city,
          query.propertyType,
          query.periods,
        );
        return { district: query.district, city: query.city, propertyType: query.propertyType, trend };
      },
      CacheTTL.MARKET_DATA,
      'price_trend',
    );
  }
}
