// SCB Admin Console - SCB Overview Dashboard Service
// Domestic network health, corridor view, local GRU & CBDC, risk & compliance

import prisma from '@/shared/database/prisma';
import { logger } from '@/infrastructure/monitoring/logger';
import { dashboardService } from '@/core/compliance/regtech/dashboard.service';
import Decimal from 'decimal.js';

export interface DomesticNetworkHealth {
  fiCount: number;
  activeFIs: number;
  paymentRails: Array<{
    railType: string;
    status: 'active' | 'degraded' | 'down';
    volume24h: number;
  }>;
  cbdcStatus: {
    totalInCirculation: number;
    wallets: {
      retail: number;
      wholesale: number;
      institutional: number;
    };
  };
  nostroVostroStatus: {
    totalAccounts: number;
    activeAccounts: number;
    apiEnabled: boolean;
  };
}

export interface CorridorView {
  corridors: Array<{
    targetSCB: string;
    targetSCBName: string;
    volume24h: number;
    latency: number;
    riskFlags: number;
    preferredSettlementAsset: string;
  }>;
}

export interface LocalGRUCBDC {
  gruBalances: {
    sr3: number;
    m0: number;
  };
  cbdcInCirculation: {
    rCBDC: number;
    wCBDC: number;
    iCBDC: number;
  };
  walletsByType: {
    retail: number;
    wholesale: number;
    institutional: number;
  };
}

export interface LocalRiskCompliance {
  sareView: {
    sovereignRisk: number;
    fiLevelExposure: Array<{
      fiId: string;
      fiName: string;
      exposure: number;
    }>;
  };
  ariAlerts: Array<{
    alertId: string;
    type: string;
    severity: string;
    description: string;
    timestamp: Date;
  }>;
  suspiciousFlows: Array<{
    flowId: string;
    description: string;
    riskLevel: string;
  }>;
}

export interface SCBOverviewDashboard {
  domesticNetwork: DomesticNetworkHealth;
  corridorView: CorridorView;
  localGRUCBDC: LocalGRUCBDC;
  riskCompliance: LocalRiskCompliance;
}

export class SCBOverviewService {
  /**
   * Get SCB overview dashboard
   */
  async getSCBOverview(scbId: string): Promise<SCBOverviewDashboard> {
    const [domesticNetwork, corridorView, localGRUCBDC, riskCompliance] = await Promise.all([
      this.getDomesticNetworkHealth(scbId),
      this.getCorridorView(scbId),
      this.getLocalGRUCBDC(scbId),
      this.getLocalRiskCompliance(scbId),
    ]);

    return {
      domesticNetwork,
      corridorView,
      localGRUCBDC,
      riskCompliance,
    };
  }

  /**
   * Get domestic network health
   */
  async getDomesticNetworkHealth(scbId: string): Promise<DomesticNetworkHealth> {
    // Get CBDC wallets
    const wallets = await prisma.cbdc_wallets.findMany({
      where: { sovereignBankId: scbId },
    });

    const cbdcInCirculation = wallets.reduce(
      (sum, w) => sum.plus(w.balance),
      new Decimal(0)
    ).toNumber();

    // Get payment rails (placeholder)
    const paymentRails = [
      {
        railType: 'RTGS',
        status: 'active' as const,
        volume24h: 0,
      },
      {
        railType: 'CBDC',
        status: 'active' as const,
        volume24h: cbdcInCirculation,
      },
    ];

    return {
      fiCount: 0, // Would query FI table
      activeFIs: 0,
      paymentRails,
      cbdcStatus: {
        totalInCirculation: cbdcInCirculation,
        wallets: {
          retail: wallets.filter((w) => w.walletType === 'retail').length,
          wholesale: wallets.filter((w) => w.walletType === 'wholesale').length,
          institutional: wallets.filter((w) => w.walletType === 'institutional').length,
        },
      },
      nostroVostroStatus: {
        totalAccounts: 0, // Would query Nostro/Vostro accounts
        activeAccounts: 0,
        apiEnabled: true,
      },
    };
  }

  /**
   * Get corridor view
   */
  async getCorridorView(scbId: string): Promise<CorridorView> {
    const oneDayAgo = new Date(Date.now() - 24 * 60 * 60 * 1000);

    // Get routes from this SCB
    const routes = await prisma.settlement_routes.findMany({
      where: {
        OR: [{ sourceBankId: scbId }, { destinationBankId: scbId }],
        status: 'active',
      },
    });

    const corridors = [];

    for (const route of routes) {
      const targetSCBId = route.sourceBankId === scbId ? route.destinationBankId : route.sourceBankId;
      const targetSCB = await prisma.sovereign_banks.findUnique({
        where: { id: targetSCBId },
      });

      // Get 24h volume
      const settlements = await prisma.atomic_settlements.findMany({
        where: {
          sourceBankId: route.sourceBankId,
          destinationBankId: route.destinationBankId,
          createdAt: { gte: oneDayAgo },
        },
      });

      const volume24h = settlements
        .filter((s: any) => s.status === 'settled')
        .reduce((sum: any, s: any) => sum.plus(s.amount), new Decimal(0))
        .toNumber();

      // Get risk flags (SRI enforcements)
      const riskFlags = await prisma.sri_enforcements.count({
        where: {
          sovereignBankId: targetSCBId,
          status: 'active',
        },
      });

      corridors.push({
        targetSCB: targetSCBId,
        targetSCBName: targetSCB?.name || 'Unknown',
        volume24h,
        latency: route.estimatedLatency || 0,
        riskFlags,
        preferredSettlementAsset: route.currencyCode,
      });
    }

    return { corridors };
  }

  /**
   * Get local GRU & CBDC
   */
  async getLocalGRUCBDC(scbId: string): Promise<LocalGRUCBDC> {
    // Get CBDC wallets
    const wallets = await prisma.cbdc_wallets.findMany({
      where: { sovereignBankId: scbId },
    });

    const rCBDC = wallets
        .filter((w: any) => w.walletType === 'retail')
        .reduce((sum: any, w: any) => sum.plus(w.balance), new Decimal(0))
      .toNumber();

    const wCBDC = wallets
        .filter((w: any) => w.walletType === 'wholesale')
        .reduce((sum: any, w: any) => sum.plus(w.balance), new Decimal(0))
      .toNumber();

    const iCBDC = wallets
        .filter((w: any) => w.walletType === 'institutional')
        .reduce((sum: any, w: any) => sum.plus(w.balance), new Decimal(0))
      .toNumber();

    return {
      gruBalances: {
        sr3: 0, // Would query GRU balances
        m0: 0,
      },
      cbdcInCirculation: {
        rCBDC,
        wCBDC,
        iCBDC,
      },
      walletsByType: {
        retail: wallets.filter((w: any) => w.walletType === 'retail').length,
        wholesale: wallets.filter((w: any) => w.walletType === 'wholesale').length,
        institutional: wallets.filter((w: any) => w.walletType === 'institutional').length,
      },
    };
  }

  /**
   * Get local risk & compliance
   */
  async getLocalRiskCompliance(scbId: string): Promise<LocalRiskCompliance> {
    // Get SRI
    const sri = await prisma.sovereign_risk_indices.findFirst({
      where: { sovereignBankId: scbId },
      orderBy: { calculatedAt: 'desc' },
    });

    // Get ARI alerts
    const dashboard = await dashboardService.getIncidentAlertsDashboard(scbId);
    const ariAlerts = (dashboard.incidentAlerts || []).map((alert, index) => ({
      alertId: `ari-${scbId}-${index}`,
      type: alert.type,
      severity: alert.severity,
      description: alert.description,
      timestamp: alert.timestamp,
    }));

    return {
      sareView: {
        sovereignRisk: sri ? parseFloat(sri.sriScore.toString()) : 0,
        fiLevelExposure: [], // Would query FI exposures
      },
      ariAlerts,
      suspiciousFlows: [], // Would query suspicious transaction patterns
    };
  }
}

export const scbOverviewService = new SCBOverviewService();

