// SCB Admin Console - Corridor & FX Policy Service
// Corridor management, FX policy, settlement asset preferences

import prisma from '@/shared/database/prisma';
import { logger } from '@/infrastructure/monitoring/logger';
import Decimal from 'decimal.js';

export interface CorridorPolicy {
  routeId: string;
  targetSCB: string;
  targetSCBName: string;
  status: 'active' | 'pending' | 'suspended';
  limits: {
    dailyCap: number;
    perTransactionLimit: number;
  };
  preferredSettlementAsset: string; // GRU, SSU, fiat
  metaverseEnabled: boolean;
}

export interface FXPolicy {
  corridors: Array<{
    corridorId: string;
    baseCurrency: string;
    quoteCurrency: string;
    spreads: {
      min: number;
      max: number;
    };
    fees: {
      min: number;
      max: number;
    };
  }>;
}

export interface CorridorPolicyDashboard {
  corridors: CorridorPolicy[];
  fxPolicy: FXPolicy;
}

export class CorridorPolicyService {
  /**
   * Get corridor & FX policy dashboard
   */
  async getCorridorPolicyDashboard(scbId: string): Promise<CorridorPolicyDashboard> {
    const [corridors, fxPolicy] = await Promise.all([
      this.getCorridors(scbId),
      this.getFXPolicy(scbId),
    ]);

    return { corridors, fxPolicy };
  }

  /**
   * Get corridors for SCB
   */
  async getCorridors(scbId: string): Promise<CorridorPolicy[]> {
    const routes = await prisma.settlementRoute.findMany({
      where: {
        OR: [{ sourceBankId: scbId }, { destinationBankId: scbId }],
        status: 'active',
      },
    });

    const corridors: CorridorPolicy[] = [];

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

      // Get 24h volume for limits
      const oneDayAgo = new Date(Date.now() - 24 * 60 * 60 * 1000);
      const settlements = await prisma.atomicSettlement.findMany({
        where: {
          sourceBankId: route.sourceBankId,
          destinationBankId: route.destinationBankId,
          createdAt: { gte: oneDayAgo },
        },
      });

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

      corridors.push({
        routeId: route.routeId,
        targetSCB: targetSCBId,
        targetSCBName: targetSCB?.name || 'Unknown',
        status: route.status === 'active' ? 'active' : 'suspended',
        limits: {
          dailyCap: dailyVolume * 1.5, // 150% of current volume
          perTransactionLimit: 10000000, // Placeholder
        },
        preferredSettlementAsset: 'SSU', // Default
        metaverseEnabled: false, // Placeholder
      });
    }

    return corridors;
  }

  /**
   * Get FX policy
   */
  async getFXPolicy(scbId: string): Promise<FXPolicy> {
    // Get FX pairs
    const fxPairs = await prisma.fxPair.findMany({
      where: { status: 'active' },
    });

    const corridors = fxPairs.map((pair) => ({
      corridorId: pair.id,
      baseCurrency: pair.baseCurrency,
      quoteCurrency: pair.quoteCurrency,
      spreads: {
        min: 0.0001,
        max: 0.01,
      },
      fees: {
        min: 0.001,
        max: 0.05,
      },
    }));

    return { corridors };
  }
}

export const corridorPolicyService = new CorridorPolicyService();

