// Risk Management Service

import { sriMonitorService } from '@/core/risk/sri/sri-monitor.service';
import { sriCalculatorService } from '@/core/risk/sri/sri-calculator.service';
import prisma from '@/shared/database/prisma';

export class RiskService {
  /**
   * Calculate counterparty credit score
   */
  async calculateCounterpartyCreditScore(counterpartyId: string): Promise<number> {
    // Use SRI as basis for counterparty credit score
    const sri = await prisma.sovereignRiskIndex.findFirst({
      where: {
        sovereignBankId: counterpartyId,
        status: 'active',
      },
    });

    if (sri) {
      const sriScore = parseFloat(sri.sriScore.toString());
      // Convert SRI (0-100, higher = riskier) to credit score (0-100, higher = better)
      return Math.max(0, 100 - sriScore);
    }

    // In production, would use ML models
    // For now, return default score
    return 75;
  }

  /**
   * Check liquidity risk
   */
  async checkLiquidityRisk(sovereignBankId: string): Promise<boolean> {
    // Check SRI for liquidity risk indicators
    const monitorResult = await sriMonitorService.monitorSRI(sovereignBankId);
    
    // High SRI indicates liquidity risk
    if (monitorResult.currentSRI > 40) {
      return true;
    }

    // In production, would also check LCR/NSFR directly
    return false;
  }

  /**
   * Monitor market manipulation
   */
  async monitorMarketManipulation(transactionId: string): Promise<boolean> {
    // Use RegTech supervision engine for pattern detection
    const transaction = await prisma.ledgerEntry.findFirst({
      where: { referenceId: transactionId },
      include: {
        debitAccount: true,
      },
    });

    if (!transaction) {
      return false;
    }

    // In production, would use supervision engine
    // For now, return false (no manipulation detected)
    return false;
  }

  /**
   * Get sovereign risk index
   */
  async getSovereignRiskIndex(sovereignBankId: string) {
    return await sriCalculatorService.calculateSRI(sovereignBankId);
  }
}

export const riskService = new RiskService();

