// FACE Stabilization Contract Service
import { Prisma } from '@prisma/client';
// Auto-stabilization: if SRI_risk > threshold: impose_rate_adjustment()

import prisma from '@/shared/database/prisma';
import { Decimal } from '@prisma/client/runtime/library';
import { v4 as uuidv4 } from 'uuid';
import { sriCalculatorService } from '@/core/risk/sri/sri-calculator.service';


export interface CreateStabilizationContractRequest {
  economyId: string;
  sriThreshold: number;
  rateAdjustmentRule: Record<string, unknown>;
  adjustmentType: 'interest_rate' | 'liquidity_rate' | 'fee_adjustment';
}

export class FaceStabilizationService {
  /**
   * Create stabilization contract
   */
  async createStabilizationContract(request: CreateStabilizationContractRequest) {
    const contractId = `FACE-STAB-${uuidv4()}`;

    // Get the face_economies record by economyId to get its id
    const economy = await prisma.face_economies.findUnique({
      where: { economyId: request.economyId },
    });

    if (!economy) {
      throw new Error(`Economy not found: ${request.economyId}`);
    }

    const contract = await prisma.face_stabilization_contracts.create({
      data: {
        id: uuidv4(),
        contractId,
        economyId: economy.id, // Use the id field, not economyId
        contractType: 'auto_stabilization',
        sriThreshold: new Decimal(request.sriThreshold),
        rateAdjustmentRule: (request.rateAdjustmentRule || {
          rule: 'if SRI_risk > threshold: impose_rate_adjustment()',
        }) as Prisma.InputJsonValue,
        adjustmentType: request.adjustmentType,
        status: 'active',
        createdAt: new Date(),
        updatedAt: new Date(),
      },
    });

    return contract;
  }

  /**
   * Check and execute stabilization contract
   */
  async checkStabilizationContract(contractId: string) {
    const contract = await prisma.face_stabilization_contracts.findUnique({
      where: { contractId },
      include: {
        face_economies: true,
      },
    });

    if (!contract) {
      throw new Error(`Stabilization contract not found: ${contractId}`);
    }

    if (contract.status !== 'active') {
      return { triggered: false, reason: 'Contract not active' };
    }

    // Get current SRI for the sovereign bank
    const sriResult = await sriCalculatorService.calculateSRI(contract.face_economies.sovereignBankId);
    const currentSRI = sriResult.sriScore;
    const threshold = parseFloat(contract.sriThreshold.toString());

    // if SRI_risk > threshold: impose_rate_adjustment()
    if (currentSRI > threshold) {
      // Calculate adjustment based on SRI excess
      const excess = currentSRI - threshold;
      const adjustmentPercentage = Math.min(excess * 0.1, 5); // Max 5% adjustment

      // In production, this would actually adjust rates in the system
      // For now, just record the adjustment
      const adjustment = {
        type: contract.adjustmentType,
        percentage: adjustmentPercentage,
        sriExcess: excess,
        timestamp: new Date().toISOString(),
      };

      // Update contract
      await prisma.face_stabilization_contracts.update({
        where: { contractId },
        data: {
          lastTriggeredAt: new Date(),
        },
      });

      return {
        triggered: true,
        currentSRI,
        threshold,
        adjustment,
      };
    }

    return {
      triggered: false,
      reason: 'SRI within acceptable threshold',
      currentSRI,
      threshold,
    };
  }

  /**
   * Get stabilization contracts for economy
   */
  async getContractsForEconomy(economyId: string) {
    return prisma.face_stabilization_contracts.findMany({
      where: { economyId },
      orderBy: {
        createdAt: 'desc',
      },
    });
  }

  /**
   * Get contract by ID
   */
  async getContract(contractId: string) {
    const contract = await prisma.face_stabilization_contracts.findUnique({
      where: { contractId },
      include: {
        face_economies: true,
      },
    });

    if (!contract) {
      throw new Error(`Stabilization contract not found: ${contractId}`);
    }

    return contract;
  }
}

export const faceStabilizationService = new FaceStabilizationService();

