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 HeatmapDataPoint,
} from '../../../domain/repositories/market-index.repository';
import { GetHeatmapQuery } from './get-heatmap.query';

export interface HeatmapDto {
  city: string;
  period: string;
  dataPoints: HeatmapDataPoint[];
}

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

  async execute(query: GetHeatmapQuery): Promise<HeatmapDto> {
    const cacheKey = CacheService.buildKey(CachePrefix.MARKET_HEATMAP, query.city, query.period);

    return this.cache.getOrSet(
      cacheKey,
      async () => {
        const dataPoints = await this.marketIndexRepo.getHeatmap(query.city, query.period);
        return { city: query.city, period: query.period, dataPoints };
      },
      CacheTTL.HEATMAP,
      'heatmap',
    );
  }
}
