// M-RTGS MACE Integration
// Collateralized RTGS via MACE engine

import prisma from '@/shared/database/prisma';
import { Decimal } from '@prisma/client/runtime/library';
import { logger } from '@/infrastructure/monitoring/logger';


export interface MaceCollateralRequest {
  settlementId: string;
  amount: string;
  currencyCode: string;
  assetType: string;
  sourceBankId: string;
}

export interface MaceCollateralResult {
  collateralized: boolean;
  collateralAmount: Decimal;
  collateralType: string;
}

export class MrtgsMaceIntegrationService {
  /**
   * Check and allocate collateral via MACE for RTGS settlement
   */
  async allocateCollateral(request: MaceCollateralRequest): Promise<MaceCollateralResult> {
    try {
      // In production, this would call MACE engine to:
      // 1. Calculate optimal collateral allocation
      // 2. Reserve collateral assets
      // 3. Return collateral details

      // For now, simplified implementation
      const amount = new Decimal(request.amount);

      // Check if bank has sufficient collateral
      const hasCollateral = await this.checkCollateralAvailability(
        request.sourceBankId,
        amount,
        request.currencyCode,
        request.assetType
      );

      if (!hasCollateral) {
        logger.warn('M-RTGS MACE: Insufficient collateral', {
          settlementId: request.settlementId,
          sourceBankId: request.sourceBankId,
          amount: amount.toString(),
        });

        return {
          collateralized: false,
          collateralAmount: new Decimal(0),
          collateralType: 'none',
        };
      }

      // Allocate collateral (simplified)
      const collateralAmount = amount.times(1.1); // 110% collateralization
      const collateralType = request.assetType === 'cbdc' ? 'cbdc' : 'fiat';

      logger.info('M-RTGS MACE: Collateral allocated', {
        settlementId: request.settlementId,
        collateralAmount: collateralAmount.toString(),
        collateralType,
      });

      return {
        collateralized: true,
        collateralAmount,
        collateralType,
      };
    } catch (error) {
      logger.error('M-RTGS MACE: Collateral allocation failed', {
        error,
        request,
      });

      return {
        collateralized: false,
        collateralAmount: new Decimal(0),
        collateralType: 'none',
      };
    }
  }

  /**
   * Check collateral availability
   */
  private async checkCollateralAvailability(
    sourceBankId: string,
    requiredAmount: Decimal,
    currencyCode: string,
    assetType: string
  ): Promise<boolean> {
    // Get bank's available balance
    const accounts = await prisma.bankAccount.findMany({
      where: {
        sovereignBankId: sourceBankId,
        currencyCode,
        assetType,
        status: 'active',
      },
    });

    const totalAvailable = accounts.reduce(
      (sum, account) => sum.plus(account.availableBalance),
      new Decimal(0)
    );

    // Check if available balance >= required amount * 1.1 (110% collateralization)
    return totalAvailable.gte(requiredAmount.times(1.1));
  }

  /**
   * Release collateral after settlement
   */
  async releaseCollateral(settlementId: string): Promise<void> {
    // In production, this would release collateral via MACE engine
    logger.info('M-RTGS MACE: Collateral released', { settlementId });
  }
}

export const mrtgsMaceIntegrationService = new MrtgsMaceIntegrationService();

