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 DistrictStatsResult,
} from '../../../domain/repositories/market-index.repository';
import { GetDistrictStatsQuery } from './get-district-stats.query';

export interface DistrictStatsDto {
  city: string;
  period: string;
  districts: DistrictStatsResult[];
}

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

  async execute(query: GetDistrictStatsQuery): Promise<DistrictStatsDto> {
    const cacheKey = CacheService.buildKey(CachePrefix.MARKET_DISTRICT, query.city, query.period);

    return this.cache.getOrSet(
      cacheKey,
      async () => {
        const districts = await this.marketIndexRepo.getDistrictStats(query.city, query.period);
        return { city: query.city, period: query.period, districts };
      },
      CacheTTL.DISTRICT_STATS,
      'district_stats',
    );
  }
}
