import { Inject, InternalServerErrorException } from '@nestjs/common';
import { QueryHandler, type IQueryHandler } from '@nestjs/cqrs';
import { CacheService, CachePrefix, CacheTTL, DomainException, LoggerService } from '@modules/shared';
import {
  AVM_SERVICE,
  type IAVMService,
  type BatchValuationResult,
} from '../../../domain/services/avm-service';
import { BatchValuationQuery } from './batch-valuation.query';

export type BatchValuationDto = BatchValuationResult[];

@QueryHandler(BatchValuationQuery)
export class BatchValuationHandler implements IQueryHandler<BatchValuationQuery> {
  constructor(
    @Inject(AVM_SERVICE) private readonly avmService: IAVMService,
    private readonly cache: CacheService,
    private readonly logger: LoggerService,
  ) {}

  async execute(query: BatchValuationQuery): Promise<BatchValuationDto> {
    try {
      const cacheKey = CacheService.buildKey(
        CachePrefix.VALUATION,
        'batch',
        ...query.propertyIds.slice().sort(),
      );

      return await this.cache.getOrSet(
        cacheKey,
        async () => {
          const items = query.propertyIds.map((propertyId) => ({ propertyId }));
          return this.avmService.estimateBatch(items);
        },
        CacheTTL.MARKET_DATA,
        'batch_valuation',
      );
    } catch (error) {
      if (error instanceof DomainException) throw error;
      this.logger.error(
        `Batch valuation failed: ${error instanceof Error ? error.message : error}`,
        error instanceof Error ? error.stack : undefined,
        this.constructor.name,
      );
      throw new InternalServerErrorException('Không thể định giá hàng loạt. Vui lòng thử lại sau.');
    }
  }
}
