// DSDM Compliance Service
// DBIS risk controls enforcement

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


export interface ComplianceCheckRequest {
  sovereignBankId: string;
  operationType: string;
  amount?: string;
}

export interface ComplianceResult {
  compliant: boolean;
  riskScore?: number;
  restrictions?: string[];
}

export class DsdmComplianceService {
  /**
   * Check compliance for debt market operation
   */
  async checkCompliance(
    request: ComplianceCheckRequest
  ): Promise<ComplianceResult> {
    // Get SRI score
    const sri = await prisma.sovereign_risk_indices.findFirst({
      where: {
        sovereignBankId: request.sovereignBankId,
        status: 'active',
      },
      orderBy: { calculatedAt: 'desc' },
    });

    if (!sri) {
      // If no SRI, allow operation but flag for review
      return {
        compliant: true,
        restrictions: ['SRI_NOT_AVAILABLE'],
      };
    }

    const sriScore = parseFloat(sri.sriScore.toString());
    const restrictions: string[] = [];

    // Check SRI-based restrictions
    if (sriScore > 60) {
      // High risk - restrict large operations
      if (request.amount) {
        const amount = parseFloat(request.amount);
        if (amount > 1000000000) { // 1 billion threshold
          restrictions.push('LARGE_OPERATION_RESTRICTED');
        }
      }
    }

    if (sriScore > 80) {
      // Very high risk - restrict all operations
      return {
        compliant: false,
        riskScore: sriScore,
        restrictions: ['ALL_OPERATIONS_RESTRICTED'],
      };
    }

    return {
      compliant: restrictions.length === 0,
      riskScore: sriScore,
      restrictions: restrictions.length > 0 ? restrictions : undefined,
    };
  }

  /**
   * Validate debt instrument issuance
   */
  async validateIssuance(
    issuerBankId: string,
    amount: string
  ): Promise<boolean> {
    const compliance = await this.checkCompliance({
      sovereignBankId: issuerBankId,
      operationType: 'issuance',
      amount,
    });

    return compliance.compliant;
  }

  /**
   * Validate rollover operation
   */
  async validateRollover(
    sovereignBankId: string,
    rolloverAmount: string
  ): Promise<boolean> {
    const compliance = await this.checkCompliance({
      sovereignBankId,
      operationType: 'rollover',
      amount: rolloverAmount,
    });

    return compliance.compliant;
  }
}

export const dsdmComplianceService = new DsdmComplianceService();

