// SRI Monitor Service
// Real-time monitoring, trigger detection (SRI > 40, > 60)

import prisma from '@/shared/database/prisma';
import { logger } from '@/infrastructure/monitoring/logger';
import { sriCalculatorService } from './sri-calculator.service';
import { sriEnforcementService } from './sri-enforcement.service';

export class SRIMonitorService {
  /**
   * Monitor SRI for a sovereign bank
   */
  async monitorSRI(sovereignBankId: string): Promise<{
    currentSRI: number;
    rating: string;
    triggers: string[];
  }> {
    // Get or calculate current SRI
    let sri = await prisma.sovereign_risk_indices.findFirst({
      where: {
        sovereignBankId,
        status: 'active',
      },
    });

    if (!sri) {
      // Calculate new SRI
      const result = await sriCalculatorService.createSRI(sovereignBankId);
      sri = await prisma.sovereign_risk_indices.findUnique({
        where: { id: result.sriId },
      });
    }

    if (!sri) {
      throw new Error('Failed to get or calculate SRI');
    }

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

    // Check triggers
    if (sriScore > 60) {
      triggers.push('sri_60');
    } else if (sriScore > 40) {
      triggers.push('sri_40');
    }

    // Check if enforcement already exists
    for (const trigger of triggers) {
      const existing = await prisma.sri_enforcements.findFirst({
        where: {
          sriId: sri.id,
          triggerLevel: trigger,
          status: 'active',
        },
      });

      if (!existing) {
        // Create enforcement
        await sriEnforcementService.createEnforcement(sri.id, sovereignBankId, trigger);
      }
    }

    return {
      currentSRI: sriScore,
      rating: sri.sriRating,
      triggers,
    };
  }

  /**
   * Monitor all sovereign banks
   */
  async monitorAllBanks(): Promise<
    Array<{
      sovereignBankId: string;
      sri: number;
      rating: string;
      triggers: string[];
    }>
  > {
    const banks = await prisma.sovereign_banks.findMany({
      where: { status: 'active' },
    });

    const results = [];
    for (const bank of banks) {
      try {
        const monitorResult = await this.monitorSRI(bank.id);
        results.push({
          sovereignBankId: bank.id,
          sri: monitorResult.currentSRI,
          rating: monitorResult.rating,
          triggers: monitorResult.triggers,
        });
      } catch (error) {
        logger.error('Error monitoring SRI for bank', {
          bankId: bank.id,
          error: error instanceof Error ? error.message : 'Unknown error',
        });
      }
    }

    return results;
  }

  /**
   * Get SRI history for a sovereign bank
   */
  async getSRIHistory(sovereignBankId: string, limit: number = 30) {
    return await prisma.sovereign_risk_indices.findMany({
      where: { sovereignBankId },
      orderBy: { calculatedAt: 'desc' },
      take: limit,
    });
  }

  /**
   * Get banks with high SRI
   */
  async getHighRiskBanks(threshold: number = 40) {
    const { Decimal } = await import('@prisma/client/runtime/library');
    const thresholdDecimal = new Decimal(threshold);
    return await prisma.sovereign_risk_indices.findMany({
      where: {
        status: 'active',
        sriScore: {
          gt: thresholdDecimal,
        },
      },
      include: {
        enforcements: {
          where: { status: 'active' },
        },
      },
      orderBy: { sriScore: 'desc' },
    });
  }
}

export const sriMonitorService = new SRIMonitorService();

