// MACE Monitoring Service
// Real-time collateral monitoring

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


export interface MonitoringRequest {
  collateralId: string;
}

export interface MonitoringResult {
  collateralId: string;
  totalValuation: string;
  haircutAdjustedValue: string;
  status: string;
  alerts: string[];
}

export class MaceMonitoringService {
  /**
   * Monitor collateral
   */
  async monitorCollateral(
    request: MonitoringRequest
  ): Promise<MonitoringResult> {
    const collaterals = await prisma.multiAssetCollateral.findMany({
      where: {
        collateralId: {
          startsWith: request.collateralId,
        },
        status: 'active',
      },
    });

    if (collaterals.length === 0) {
      throw new Error(`Collateral not found: ${request.collateralId}`);
    }

    // Calculate total valuation
    const totalValuation = collaterals.reduce(
      (sum, coll) => sum.plus(coll.valuation),
      new Decimal(0)
    );

    // Calculate haircut-adjusted value
    let haircutAdjustedValue = new Decimal(0);
    const alerts: string[] = [];

    for (const coll of collaterals) {
      const haircut = await this.getHaircut(coll.assetType);
      const adjustedValue = coll.valuation.mul(new Decimal(100).minus(haircut)).div(100);
      haircutAdjustedValue = haircutAdjustedValue.plus(adjustedValue);

      // Check for alerts
      if (coll.valuation.lessThan(new Decimal(1000))) {
        alerts.push(`Low valuation for ${coll.assetType}: ${coll.valuation.toString()}`);
      }
    }

    // Check overall status
    let status = 'healthy';
    if (haircutAdjustedValue.lessThan(totalValuation.mul(0.9))) {
      status = 'warning';
      alerts.push('Haircut-adjusted value below 90% of total valuation');
    }

    return {
      collateralId: request.collateralId,
      totalValuation: totalValuation.toString(),
      haircutAdjustedValue: haircutAdjustedValue.toString(),
      status,
      alerts,
    };
  }

  /**
   * Get haircut
   */
  private async getHaircut(assetType: string): Promise<Decimal> {
    const haircut = await prisma.collateralHaircut.findFirst({
      where: {
        assetType,
        status: 'active',
      },
    });

    return haircut ? haircut.haircutRate : new Decimal(5); // Default 5%
  }

  /**
   * Get all active collaterals
   */
  async getActiveCollaterals(): Promise<any[]> {
    const collaterals = await prisma.multiAssetCollateral.findMany({
      where: { status: 'active' },
      orderBy: { allocatedAt: 'desc' },
    });

    return collaterals;
  }
}

export const maceMonitoringService = new MaceMonitoringService();

