import { CommandHandler, type ICommandHandler } from '@nestjs/cqrs';
import { estimateTransferListingPrices, type FurniturePricingInput } from '../../../domain/services/furniture-pricing.service';
import { EstimateTransferPricesCommand } from './estimate-transfer-prices.command';

@CommandHandler(EstimateTransferPricesCommand)
export class EstimateTransferPricesHandler implements ICommandHandler<EstimateTransferPricesCommand> {
  async execute(cmd: EstimateTransferPricesCommand) {
    const inputs: FurniturePricingInput[] = cmd.items.map((item) => ({
      category: item.category,
      condition: item.condition,
      originalPriceVND: BigInt(Math.round(item.originalPriceVND)),
      purchaseYear: item.purchaseYear,
      brand: item.brand,
    }));

    const { estimates, totalEstimateVND, avgConfidence } = estimateTransferListingPrices(inputs);

    return {
      estimates: estimates.map((e) => ({
        estimatedPriceVND: e.estimatedPriceVND.toString(),
        confidence: Math.round(e.confidence * 100) / 100,
        factors: e.factors,
      })),
      totalEstimateVND: totalEstimateVND.toString(),
      avgConfidence: Math.round(avgConfidence * 100) / 100,
    };
  }
}
