import { Inject } from '@nestjs/common';
import { QueryHandler, type IQueryHandler } from '@nestjs/cqrs';
import { CacheService, CachePrefix, CacheTTL } from '@modules/shared';
import {
  NEIGHBORHOOD_SCORE_SERVICE,
  type INeighborhoodScoreService,
  type NeighborhoodScoreResult,
} from '../../../domain/services/neighborhood-score.service';
import { GetNeighborhoodScoreQuery } from './get-neighborhood-score.query';

@QueryHandler(GetNeighborhoodScoreQuery)
export class GetNeighborhoodScoreHandler implements IQueryHandler<GetNeighborhoodScoreQuery> {
  constructor(
    @Inject(NEIGHBORHOOD_SCORE_SERVICE)
    private readonly scoreService: INeighborhoodScoreService,
    private readonly cache: CacheService,
  ) {}

  async execute(query: GetNeighborhoodScoreQuery): Promise<NeighborhoodScoreResult> {
    const cacheKey = CacheService.buildKey(
      CachePrefix.NEIGHBORHOOD_SCORE,
      query.district,
      query.city,
    );

    return this.cache.getOrSet(
      cacheKey,
      async () => {
        // Return cached DB score if available, otherwise calculate
        const existing = await this.scoreService.getScore(query.district, query.city);
        if (existing) return existing;

        return this.scoreService.calculateAndSave(query.district, query.city);
      },
      CacheTTL.NEIGHBORHOOD_SCORE,
      'neighborhood-score',
    );
  }
}
