import { Injectable, Inject, Logger } from '@nestjs/common';
import {
  AI_AGENT_CLIENT,
  IAiAgentClient,
  AgentPricingRequest,
} from '../../domain/ports/ai-agent.client.interface';
import { PricingRequestDto, PricingResponseDto } from '../../interface/http/dto/pricing.dto';
import { PricingSuggestion } from '../../domain/value-objects/pricing-suggestion.vo';

@Injectable()
export class AiPricingService {
  private readonly logger = new Logger(AiPricingService.name);

  constructor(
    @Inject(AI_AGENT_CLIENT) private readonly agentClient: IAiAgentClient,
  ) {}

  async getSuggestion(req: PricingRequestDto): Promise<PricingResponseDto> {
    const agentReq: AgentPricingRequest = {
      couponId: req.couponId,
      faceValue: req.faceValue,
      daysToExpiry: req.daysToExpiry,
      totalDays: req.totalDays,
      redemptionRate: req.redemptionRate,
      liquidityPremium: req.liquidityPremium,
    };

    try {
      const raw = await this.agentClient.pricing(agentReq);
      const result = PricingSuggestion.fromResponse(raw);
      return result.toPlain();
    } catch (error) {
      this.logger.warn(`External AI pricing unavailable: ${error.message}`);
    }

    // Fallback: local 3-factor pricing model via domain value object
    const result = PricingSuggestion.fromLocalModel({
      faceValue: req.faceValue,
      daysToExpiry: req.daysToExpiry,
      totalDays: req.totalDays,
      redemptionRate: req.redemptionRate,
      liquidityPremium: req.liquidityPremium,
    });
    return result.toPlain();
  }
}
