import { Injectable, Inject } from '@nestjs/common';
import { CREDIT_METRIC_REPOSITORY, ICreditMetricRepository } from '../../domain/repositories/credit-metric.repository.interface';

@Injectable()
export class CreditScoringService {
  constructor(
    @Inject(CREDIT_METRIC_REPOSITORY)
    private readonly creditMetricRepo: ICreditMetricRepository,
  ) {}

  /**
   * 4-factor credit scoring: 35% redemption + 25% breakage + 20% tenure + 20% satisfaction
   * Score: 0-100, Levels: A(80+), B(60-79), C(40-59), D(20-39), F(<20)
   */
  calculateScore(params: {
    redemptionRate: number;
    breakageRate: number;
    tenureDays: number;
    satisfactionScore: number;
  }): { score: number; level: string } {
    const redemptionScore = Math.min(100, params.redemptionRate * 100) * 0.35;
    const breakageScore = Math.min(100, (1 - params.breakageRate) * 100) * 0.25;
    const tenureScore = Math.min(100, (params.tenureDays / 365) * 100) * 0.20;
    const satisfactionPart = Math.min(100, params.satisfactionScore) * 0.20;
    const score = Math.round(redemptionScore + breakageScore + tenureScore + satisfactionPart);
    const level = score >= 80 ? 'A' : score >= 60 ? 'B' : score >= 40 ? 'C' : score >= 20 ? 'D' : 'F';
    return { score, level };
  }

  async saveMetric(
    issuerId: string,
    params: {
      redemptionRate: number;
      breakageRate: number;
      tenureDays: number;
      satisfactionScore: number;
    },
  ) {
    const { score, level } = this.calculateScore(params);
    return this.creditMetricRepo.create({
      issuerId,
      redemptionRate: String(params.redemptionRate),
      breakageRate: String(params.breakageRate),
      tenureDays: params.tenureDays,
      satisfactionScore: String(params.satisfactionScore),
      compositeScore: String(score),
      scoreLevel: level,
    });
  }

  async getLatestMetric(issuerId: string) {
    return this.creditMetricRepo.findLatestByIssuerId(issuerId);
  }
}
