import { Injectable, Inject, Logger } from '@nestjs/common';
import {
  AI_AGENT_CLIENT,
  IAiAgentClient,
  AgentCreditScoreRequest,
} from '../../domain/ports/ai-agent.client.interface';
import { CreditScoreRequestDto, CreditScoreResponseDto } from '../../interface/http/dto/credit-score.dto';
import { CreditScoreResult } from '../../domain/value-objects/credit-score-result.vo';

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

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

  async getScore(req: CreditScoreRequestDto): Promise<CreditScoreResponseDto> {
    const agentReq: AgentCreditScoreRequest = {
      userId: req.userId,
      issuerId: req.issuerId,
      redemptionRate: req.redemptionRate,
      breakageRate: req.breakageRate,
      tenureDays: req.tenureDays,
      satisfactionScore: req.satisfactionScore,
    };

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

    // Fallback: local 4-factor calculation via domain value object
    const result = CreditScoreResult.fromFactors({
      redemptionRate: req.redemptionRate,
      breakageRate: req.breakageRate,
      tenureDays: req.tenureDays,
      satisfactionScore: req.satisfactionScore,
    });
    return result.toPlain();
  }
}
