// GRU API Routes

import { Router } from 'express';
import { gruService } from './gru-service';
import { gruValuationService } from './gru-valuation.service';
import { gruBondsService } from './gru-bonds.service';
import { gruLiquidityLoopService } from './gru-liquidity-loop.service';
import { gruIndexService } from './gru-index.service';
import { gruDerivativesService } from './gru-derivatives.service';
import { gruDerivativesPricingService } from './gru-derivatives-pricing.service';
import { gruYieldCurveService } from './gru-yield-curve.service';
import { gruIssuanceService } from './gru-issuance.service';
import { gruLegalRegistrationService } from './gru-legal-registration.service';
import { gruAuditService } from './gru-audit.service';
import { gruRegulatoryClassificationService } from './gru-regulatory-classification.service';
import { gruSupranationalGovernanceService } from './gru-supranational-governance.service';
import { gruLegalFrameworkService } from './gru-legal-framework.service';
import { gruSettlementPipelineService } from './gru-settlement-pipeline.service';
import { gruTransparencyService } from './gru-transparency.service';
import { gruAdoptionService } from './gru-adoption.service';
import { gruStressTestService } from './gru-stress-test.service';
import { gruTemporalStressService } from './gru-temporal-stress.service';
import { gruAdvancedOverlaysService } from './gru-advanced-overlays.service';
import { gruSimulationTablesService } from './gru-simulation-tables.service';
import { gruBondStressService } from './gru-bond-stress.service';
import { gruReservePoolStressService } from './gru-reserve-pool-stress.service';
import { gruOmegaReconciliationService } from './gru-omega-reconciliation.service';
import { gruTemporalSettlementService } from './gru-temporal-settlement.service';
import { gruChronoFxService } from './gru-chrono-fx.service';
import { gruSupranationalService } from './gru-supranational.service';
import { gruReservePoolService } from './gru-reserve-pool.service';
import { gruSdrService } from './gru-sdr.service';
import { gruSupranationalIssuanceService } from './gru-supranational-issuance.service';
import { gruLegalInstrumentsService } from './gru-legal-instruments.service';
import { gruSupranationalSettlementService } from './gru-supranational-settlement.service';
import { gruSareIntegrationService } from './gru-sare-integration.service';
import { gruAriIntegrationService } from './gru-ari-integration.service';
import { zeroTrustAuthMiddleware } from '@/integration/api-gateway/middleware/auth.middleware';
import bondMarketsRoutes from './gru-bond-markets.routes';
import operationsRoutes from './gru-operations.routes';

const router = Router();

// Volume III: Bond Markets Routes
router.use('/bond-markets', zeroTrustAuthMiddleware, bondMarketsRoutes);

// Volume IV: GRU Banking Operations Manual Routes
router.use('/', zeroTrustAuthMiddleware, operationsRoutes);

/**
 * @route POST /api/gru/convert
 * @desc Convert between GRU unit types
 */
router.post(
  '/convert',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const result = await gruService.convertGruUnits(req.body);
      res.json(result);
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route GET /api/gru/unit/:gruUnitId
 * @desc Get GRU unit by ID
 */
router.get(
  '/unit/:gruUnitId',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const unit = await gruService.getGruUnit(req.params.gruUnitId);
      if (!unit) {
        return res.status(404).json({ error: 'GRU unit not found' });
      }
      res.json(unit);
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route GET /api/gru/units/bank/:sovereignBankId
 * @desc Get GRU units for a bank
 */
router.get(
  '/units/bank/:sovereignBankId',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const units = await gruService.getGruUnitsForBank(
        req.params.sovereignBankId
      );
      res.json(units);
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route POST /api/gru/valuation
 * @desc Calculate GRU valuation through XAU triangulation
 */
router.post(
  '/valuation',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const result = await gruValuationService.calculateGruValuation(req.body);
      res.json(result);
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route GET /api/gru/valuation/history
 * @desc Get triangulation history
 */
router.get(
  '/valuation/history',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const gruUnitId = req.query.gruUnitId as string | undefined;
      const limit = parseInt(req.query.limit as string) || 100;
      const history = await gruValuationService.getTriangulationHistory(
        gruUnitId,
        limit
      );
      res.json(history);
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route POST /api/gru/bond/issue
 * @desc Issue GRU-linked bond
 */
router.post(
  '/bond/issue',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const result = await gruBondsService.issueGruBond(req.body);
      res.json(result);
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route GET /api/gru/bond/:bondId
 * @desc Get bond by ID
 */
router.get(
  '/bond/:bondId',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const bond = await gruBondsService.getBond(req.params.bondId);
      if (!bond) {
        return res.status(404).json({ error: 'Bond not found' });
      }
      res.json(bond);
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route GET /api/gru/bonds/bank/:sovereignBankId
 * @desc Get bonds for a bank
 */
router.get(
  '/bonds/bank/:sovereignBankId',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const bonds = await gruBondsService.getBondsForBank(
        req.params.sovereignBankId
      );
      res.json(bonds);
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route POST /api/gru/bond/:bondId/coupon
 * @desc Pay bond coupon
 */
router.post(
  '/bond/:bondId/coupon',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const paymentId = await gruBondsService.payBondCoupon(req.params.bondId);
      res.json({ paymentId, bondId: req.params.bondId });
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route POST /api/gru/bond/:bondId/redeem
 * @desc Redeem bond at maturity
 */
router.post(
  '/bond/:bondId/redeem',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const bondId = await gruBondsService.redeemBond(req.params.bondId);
      res.json({ bondId, status: 'redeemed' });
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route POST /api/gru/liquidity-loop
 * @desc Execute GRU liquidity loop
 */
router.post(
  '/liquidity-loop',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const result = await gruLiquidityLoopService.executeLiquidityLoop(req.body);
      res.json(result);
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route GET /api/gru/liquidity-loop/:loopId
 * @desc Get liquidity loop by ID
 */
router.get(
  '/liquidity-loop/:loopId',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const loop = await gruLiquidityLoopService.getLiquidityLoop(
        req.params.loopId
      );
      if (!loop) {
        return res.status(404).json({ error: 'Liquidity loop not found' });
      }
      res.json(loop);
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route GET /api/gru/liquidity-loops/bank/:sovereignBankId
 * @desc Get liquidity loops for a bank
 */
router.get(
  '/liquidity-loops/bank/:sovereignBankId',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const loops = await gruLiquidityLoopService.getLiquidityLoopsForBank(
        req.params.sovereignBankId
      );
      res.json(loops);
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route POST /api/gru/index/initialize
 * @desc Initialize GRU indexes
 */
router.post(
  '/index/initialize',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      await gruIndexService.initializeIndexes();
      res.json({ message: 'GRU indexes initialized successfully' });
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route GET /api/gru/index/:indexCode
 * @desc Get index by code
 */
router.get(
  '/index/:indexCode',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const index = await gruIndexService.getIndex(
        req.params.indexCode as any
      );
      if (!index) {
        return res.status(404).json({ error: 'Index not found' });
      }
      res.json(index);
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route GET /api/gru/index
 * @desc Get all indexes
 */
router.get(
  '/index',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const indexes = await gruIndexService.getAllIndexes();
      res.json(indexes);
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route POST /api/gru/index/update
 * @desc Update index value
 */
router.post(
  '/index/update',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const result = await gruIndexService.updateIndex(req.body);
      res.json(result);
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route POST /api/gru/index/calculate
 * @desc Calculate index value from asset prices
 */
router.post(
  '/index/calculate',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const { indexCode, assetPrices } = req.body;
      const value = await gruIndexService.calculateIndexValue(
        indexCode,
        assetPrices
      );
      res.json({ indexCode, calculatedValue: value.toString() });
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route GET /api/gru/index/:indexCode/history
 * @desc Get index price history
 */
router.get(
  '/index/:indexCode/history',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const limit = parseInt(req.query.limit as string) || 100;
      const startDate = req.query.startDate
        ? new Date(req.query.startDate as string)
        : undefined;
      const endDate = req.query.endDate
        ? new Date(req.query.endDate as string)
        : undefined;

      const history = await gruIndexService.getIndexHistory(
        req.params.indexCode as any,
        limit,
        startDate,
        endDate
      );
      res.json(history);
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route GET /api/gru/index/valuation-matrix
 * @desc Get GRU valuation matrix
 */
router.get(
  '/index/valuation-matrix',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const matrix = await gruIndexService.getValuationMatrix();
      // Convert Decimal to string for JSON response
      const serialized: Record<string, Record<string, string>> = {};
      for (const [tier, indexes] of Object.entries(matrix)) {
        serialized[tier] = {};
        for (const [indexCode, value] of Object.entries(indexes)) {
          serialized[tier][indexCode] = value.toString();
        }
      }
      res.json(serialized);
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route POST /api/gru/derivatives/futures
 * @desc Create GRU futures contract
 */
router.post(
  '/derivatives/futures',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const derivativeId = await gruDerivativesService.createFuturesContract(
        req.body
      );
      res.json({ derivativeId, status: 'created' });
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route POST /api/gru/derivatives/swap
 * @desc Create GRU swap
 */
router.post(
  '/derivatives/swap',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const derivativeId = await gruDerivativesService.createSwap(req.body);
      res.json({ derivativeId, status: 'created' });
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route POST /api/gru/derivatives/option
 * @desc Create GRU option
 */
router.post(
  '/derivatives/option',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const derivativeId = await gruDerivativesService.createOption(req.body);
      res.json({ derivativeId, status: 'created' });
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route GET /api/gru/derivatives/:derivativeId
 * @desc Get derivative by ID
 */
router.get(
  '/derivatives/:derivativeId',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const derivative = await gruDerivativesService.getDerivative(
        req.params.derivativeId
      );
      if (!derivative) {
        return res.status(404).json({ error: 'Derivative not found' });
      }
      res.json(derivative);
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route GET /api/gru/derivatives/bank/:sovereignBankId
 * @desc Get derivatives for a bank
 */
router.get(
  '/derivatives/bank/:sovereignBankId',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const status = req.query.status as string | undefined;
      const derivatives = await gruDerivativesService.getDerivativesForBank(
        req.params.sovereignBankId,
        status
      );
      res.json(derivatives);
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route POST /api/gru/derivatives/:derivativeId/mark-to-market
 * @desc Mark derivative to market
 */
router.post(
  '/derivatives/:derivativeId/mark-to-market',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const markToMarket = await gruDerivativesService.markToMarket(
        req.params.derivativeId
      );
      res.json({ derivativeId: req.params.derivativeId, markToMarket: markToMarket.toString() });
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route POST /api/gru/derivatives/option/:optionId/exercise
 * @desc Exercise option
 */
router.post(
  '/derivatives/option/:optionId/exercise',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const optionId = await gruDerivativesService.exerciseOption(
        req.params.optionId
      );
      res.json({ optionId, status: 'exercised' });
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route POST /api/gru/derivatives/swap/:swapId/payment
 * @desc Process swap payment
 */
router.post(
  '/derivatives/swap/:swapId/payment',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const paymentId = await gruDerivativesService.processSwapPayment(
        req.params.swapId
      );
      res.json({ paymentId, swapId: req.params.swapId, status: 'processed' });
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route POST /api/gru/yield-curve/update
 * @desc Update all yield curves
 */
router.post(
  '/yield-curve/update',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      await gruYieldCurveService.updateAllYieldCurves();
      res.json({ message: 'All yield curves updated successfully' });
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route GET /api/gru/yield-curve/:curveType
 * @desc Get current yield curve
 */
router.get(
  '/yield-curve/:curveType',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const curve = await gruYieldCurveService.getCurrentYieldCurve(
        req.params.curveType as any
      );
      if (!curve) {
        return res.status(404).json({ error: 'Yield curve not found' });
      }
      res.json(curve);
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route GET /api/gru/yield-curve
 * @desc Get all yield curves
 */
router.get(
  '/yield-curve',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const curves = await gruYieldCurveService.getAllYieldCurves();
      res.json(curves);
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route GET /api/gru/yield-curve/:curveType/yield/:maturityMonths
 * @desc Get yield for specific maturity
 */
router.get(
  '/yield-curve/:curveType/yield/:maturityMonths',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const maturityMonths = parseInt(req.params.maturityMonths);
      const yieldValue = await gruYieldCurveService.getYieldForMaturity(
        req.params.curveType as any,
        maturityMonths
      );
      res.json({
        curveType: req.params.curveType,
        maturityMonths,
        yield: yieldValue.toString(),
      });
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route POST /api/gru/issuance
 * @desc Issue GRU with legal classification
 */
router.post(
  '/issuance',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const result = await gruIssuanceService.issueGru(req.body);
      res.json(result);
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route GET /api/gru/issuance/:issuanceId
 * @desc Get issuance by ID
 */
router.get(
  '/issuance/:issuanceId',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const issuance = await gruIssuanceService.getIssuance(
        req.params.issuanceId
      );
      if (!issuance) {
        return res.status(404).json({ error: 'Issuance not found' });
      }
      res.json(issuance);
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route GET /api/gru/issuance/bank/:sovereignBankId
 * @desc Get issuances for a bank
 */
router.get(
  '/issuance/bank/:sovereignBankId',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const issuanceClass = req.query.issuanceClass as string | undefined;
      const status = req.query.status as string | undefined;
      const issuances = await gruIssuanceService.getIssuancesForBank(
        req.params.sovereignBankId,
        issuanceClass as any,
        status
      );
      res.json(issuances);
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route POST /api/gru/issuance/:issuanceId/approve
 * @desc Approve issuance
 */
router.post(
  '/issuance/:issuanceId/approve',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      await gruIssuanceService.approveIssuance(req.params.issuanceId);
      res.json({ issuanceId: req.params.issuanceId, status: 'approved' });
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route POST /api/gru/issuance/:issuanceId/suspend
 * @desc Suspend issuance
 */
router.post(
  '/issuance/:issuanceId/suspend',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const reason = req.body.reason || 'No reason provided';
      await gruIssuanceService.suspendIssuance(req.params.issuanceId, reason);
      res.json({ issuanceId: req.params.issuanceId, status: 'suspended' });
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route POST /api/gru/issuance/:issuanceId/revoke
 * @desc Revoke issuance
 */
router.post(
  '/issuance/:issuanceId/revoke',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const reason = req.body.reason || 'No reason provided';
      await gruIssuanceService.revokeIssuance(req.params.issuanceId, reason);
      res.json({ issuanceId: req.params.issuanceId, status: 'revoked' });
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route GET /api/gru/registration/:registrationCode
 * @desc Get registration by code
 */
router.get(
  '/registration/:registrationCode',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const registration = await gruLegalRegistrationService.getRegistrationByCode(
        req.params.registrationCode
      );
      if (!registration) {
        return res.status(404).json({ error: 'Registration not found' });
      }
      res.json(registration);
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route GET /api/gru/registration/issuance/:issuanceId
 * @desc Get registrations for issuance
 */
router.get(
  '/registration/issuance/:issuanceId',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const registrations = await gruLegalRegistrationService.getRegistrationsForIssuance(
        req.params.issuanceId
      );
      res.json(registrations);
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route POST /api/gru/registration/verify
 * @desc Verify registration code
 */
router.post(
  '/registration/verify',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const { registrationCode, registrationType } = req.body;
      const isValid = await gruLegalRegistrationService.verifyRegistrationCode(
        registrationCode,
        registrationType
      );
      res.json({ registrationCode, registrationType, isValid });
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route GET /api/gru/audit/:auditId
 * @desc Get audit by ID
 */
router.get(
  '/audit/:auditId',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const audit = await gruAuditService.getAudit(req.params.auditId);
      if (!audit) {
        return res.status(404).json({ error: 'Audit not found' });
      }
      res.json(audit);
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route GET /api/gru/audit/issuance/:issuanceId
 * @desc Get audits for issuance
 */
router.get(
  '/audit/issuance/:issuanceId',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const audits = await gruAuditService.getAuditsForIssuance(
        req.params.issuanceId
      );
      res.json(audits);
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route POST /api/gru/audit/xau-triangulation
 * @desc Perform XAU triangulation audit
 */
router.post(
  '/audit/xau-triangulation',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const { issuanceId, gruUnitId, metalIndexLink } = req.body;
      const auditId = await gruAuditService.performXauTriangulationAudit(
        issuanceId,
        gruUnitId,
        metalIndexLink
      );
      res.json({ auditId, issuanceId, status: 'completed' });
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route POST /api/gru/audit/index-signature
 * @desc Perform index signature consistency check
 */
router.post(
  '/audit/index-signature',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const { issuanceId, metalIndexLink } = req.body;
      const auditId = await gruAuditService.performIndexSignatureConsistencyCheck(
        issuanceId,
        metalIndexLink
      );
      res.json({ auditId, issuanceId, status: 'completed' });
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route POST /api/gru/audit/metal-link
 * @desc Perform metal link verification
 */
router.post(
  '/audit/metal-link',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const { issuanceId, metalIndexLink } = req.body;
      const auditId = await gruAuditService.performMetalLinkVerification(
        issuanceId,
        metalIndexLink
      );
      res.json({ auditId, issuanceId, status: 'completed' });
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route POST /api/gru/stress-test
 * @desc Run GRU stress test
 */
router.post(
  '/stress-test',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const result = await gruStressTestService.runStressTest(req.body);
      res.json(result);
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route GET /api/gru/stress-test/:testId
 * @desc Get stress test by ID
 */
router.get(
  '/stress-test/:testId',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const test = await gruStressTestService.getStressTest(
        req.params.testId
      );
      if (!test) {
        return res.status(404).json({ error: 'Stress test not found' });
      }
      res.json(test);
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route GET /api/gru/stress-test/bank/:sovereignBankId
 * @desc Get stress tests for a bank
 */
router.get(
  '/stress-test/bank/:sovereignBankId',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const status = req.query.status as string | undefined;
      const tests = await gruStressTestService.getStressTestsForBank(
        req.params.sovereignBankId,
        status
      );
      res.json(tests);
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route POST /api/gru/stress/simulation-table
 * @desc Generate simulation tables
 */
router.post(
  '/stress/simulation-table',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const { tableType, parameters } = req.body;
      let result;

      if (tableType === 'price_shock') {
        result = await gruSimulationTablesService.generatePriceShockTable(
          parameters?.xauShockPercent
        );
      } else if (tableType === 'bond_stress') {
        result = await gruSimulationTablesService.generateBondStressTable(
          parameters?.stressType
        );
      } else if (tableType === 'regional_reserve_pool') {
        result =
          await gruSimulationTablesService.generateRegionalReservePoolTable(
            parameters?.region
          );
      } else {
        return res.status(400).json({ error: 'Invalid table type' });
      }

      res.json(result);
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route GET /api/gru/stress/tables/:tableType
 * @desc Get simulation tables
 */
router.get(
  '/stress/tables/:tableType',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const table = await gruSimulationTablesService.getSimulationTable(
        req.params.tableType,
        req.query as any
      );
      if (!table) {
        return res.status(404).json({ error: 'Simulation table not found' });
      }
      res.json(table);
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route POST /api/gru/stress/bond
 * @desc Run bond stress tests
 */
router.post(
  '/stress/bond',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const result = await gruBondStressService.runBondStressTest(req.body);
      res.json(result);
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route GET /api/gru/stress/bond/:bondId
 * @desc Get bond stress tests
 */
router.get(
  '/stress/bond/:bondId',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const tests = await gruBondStressService.getBondStressTests(
        req.params.bondId
      );
      res.json(tests);
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route POST /api/gru/stress/reserve-pool
 * @desc Run reserve pool stress
 */
router.post(
  '/stress/reserve-pool',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const result = await gruReservePoolStressService.runReservePoolStress(
        req.body
      );
      res.json(result);
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route GET /api/gru/stress/reserve-pool/:poolId
 * @desc Get reserve pool
 */
router.get(
  '/stress/reserve-pool/:poolId',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const pool = await gruReservePoolStressService.getReservePool(
        req.params.poolId as 'SR-1' | 'SR-2' | 'SR-3'
      );
      if (!pool) {
        return res.status(404).json({ error: 'Reserve pool not found' });
      }
      res.json(pool);
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route POST /api/gru/stress/temporal
 * @desc Run temporal stress tests
 */
router.post(
  '/stress/temporal',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const { temporalType, parameters } = req.body;
      let result;

      if (temporalType === 'retrocausal') {
        result = await gruTemporalStressService.runRetrocausalStressTest(
          parameters || {}
        );
      } else if (temporalType === 'predictive') {
        result = await gruTemporalStressService.runPredictiveStressTest(
          parameters || {}
        );
      } else if (temporalType === 'omega_layer') {
        result = await gruTemporalStressService.runOmegaLayerStabilityTest();
      } else {
        return res.status(400).json({ error: 'Invalid temporal type' });
      }

      res.json(result);
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route POST /api/gru/stress/omega-reconcile
 * @desc Run Ω-Layer reconciliation
 */
router.post(
  '/stress/omega-reconcile',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const { testId } = req.body;
      if (!testId) {
        return res.status(400).json({ error: 'testId is required' });
      }
      const result = await gruOmegaReconciliationService.reconcilePostStress(
        testId
      );
      res.json(result);
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route POST /api/gru/stress/advanced-overlay
 * @desc Run advanced overlays
 */
router.post(
  '/stress/advanced-overlay',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const { overlayType, parameters, testId } = req.body;
      let result;

      if (overlayType === 'metaverse') {
        result = await gruAdvancedOverlaysService.runMetaverseEconomicShock(
          parameters || {}
        );
      } else if (overlayType === 'quantum') {
        result = await gruAdvancedOverlaysService.runQuantumStressOverlay(
          parameters || {}
        );
      } else if (overlayType === 'temporal_compression') {
        result = await gruAdvancedOverlaysService.runTemporalCompressionTest(
          parameters || {}
        );
      } else if (overlayType === 'all') {
        result = await gruAdvancedOverlaysService.runAllAdvancedOverlays(testId);
      } else {
        return res.status(400).json({ error: 'Invalid overlay type' });
      }

      res.json(result);
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route POST /api/gru/temporal-settlement
 * @desc Execute temporal settlement
 */
router.post(
  '/temporal-settlement',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const result = await gruTemporalSettlementService.executeTemporalSettlement(
        req.body
      );
      res.json(result);
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route GET /api/gru/temporal-settlement/:settlementId
 * @desc Get temporal settlement by ID
 */
router.get(
  '/temporal-settlement/:settlementId',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const settlement = await gruTemporalSettlementService.getTemporalSettlement(
        req.params.settlementId
      );
      if (!settlement) {
        return res.status(404).json({ error: 'Temporal settlement not found' });
      }
      res.json(settlement);
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route GET /api/gru/temporal-settlement/bank/:sovereignBankId
 * @desc Get temporal settlements for a bank
 */
router.get(
  '/temporal-settlement/bank/:sovereignBankId',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const temporalState = req.query.temporalState as string | undefined;
      const status = req.query.status as string | undefined;
      const settlements = await gruTemporalSettlementService.getTemporalSettlementsForBank(
        req.params.sovereignBankId,
        temporalState,
        status
      );
      res.json(settlements);
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route POST /api/gru/chrono-fx
 * @desc Calculate chrono-FX rate
 */
router.post(
  '/chrono-fx',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const result = await gruChronoFxService.calculateChronoFx(req.body);
      res.json(result);
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route GET /api/gru/chrono-fx/:chronoFxId
 * @desc Get chrono-FX by ID
 */
router.get(
  '/chrono-fx/:chronoFxId',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const chronoFx = await gruChronoFxService.getChronoFx(
        req.params.chronoFxId
      );
      if (!chronoFx) {
        return res.status(404).json({ error: 'Chrono-FX not found' });
      }
      res.json(chronoFx);
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route GET /api/gru/chrono-fx/settlement/:settlementId
 * @desc Get chrono-FX for settlement
 */
router.get(
  '/chrono-fx/settlement/:settlementId',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const chronoFx = await gruChronoFxService.getChronoFxForSettlement(
        req.params.settlementId
      );
      res.json(chronoFx);
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route POST /api/gru/chrono-fx/interplanetary-delay
 * @desc Calculate interplanetary transmission delay
 */
router.post(
  '/chrono-fx/interplanetary-delay',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const { sourcePlanet, targetPlanet } = req.body;
      const delay = gruChronoFxService.calculateInterplanetaryDelay(
        sourcePlanet,
        targetPlanet
      );
      res.json({
        sourcePlanet,
        targetPlanet,
        delaySeconds: delay,
        delayMinutes: Math.round(delay / 60),
      });
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route POST /api/gru/supranational/reserve
 * @desc Create supranational reserve
 */
router.post(
  '/supranational/reserve',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const reserveId = await gruSupranationalService.createSupranationalReserve(
        req.body
      );
      res.json({ reserveId, status: 'created' });
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route GET /api/gru/supranational/reserve/:reserveId
 * @desc Get supranational reserve by ID
 */
router.get(
  '/supranational/reserve/:reserveId',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const reserve = await gruSupranationalService.getSupranationalReserve(
        req.params.reserveId
      );
      if (!reserve) {
        return res.status(404).json({ error: 'Reserve not found' });
      }
      res.json(reserve);
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route GET /api/gru/supranational/reserve/class/:reserveClass
 * @desc Get reserves by class
 */
router.get(
  '/supranational/reserve/class/:reserveClass',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const reserves = await gruSupranationalService.getReservesByClass(
        req.params.reserveClass as any
      );
      res.json(reserves);
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route POST /api/gru/supranational/reserve/allocation
 * @desc Allocate reserve quota
 */
router.post(
  '/supranational/reserve/allocation',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const allocationId = await gruSupranationalService.allocateReserveQuota(
        req.body
      );
      res.json({ allocationId, status: 'allocated' });
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route POST /api/gru/supranational/stabilization-fund
 * @desc Create regional stabilization fund
 */
router.post(
  '/supranational/stabilization-fund',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const { reserveId, fundName, region, fundSize } = req.body;
      const fundId = await gruSupranationalService.createRegionalStabilizationFund(
        reserveId,
        fundName,
        region,
        fundSize
      );
      res.json({ fundId, status: 'created' });
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route POST /api/gru/supranational/sdr
 * @desc Create GRU-Backed SDR Alternative
 */
router.post(
  '/supranational/sdr',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const result = await gruSupranationalService.createGruBackedSdr(
        req.body
      );
      res.json(result);
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route GET /api/gru/supranational/sdr/:sdrId
 * @desc Get SDR alternative by ID
 */
router.get(
  '/supranational/sdr/:sdrId',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const sdr = await gruSupranationalService.getSdrAlternative(
        req.params.sdrId
      );
      if (!sdr) {
        return res.status(404).json({ error: 'SDR alternative not found' });
      }
      res.json(sdr);
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route GET /api/gru/supranational/sdr
 * @desc Get all active SDR alternatives
 */
router.get(
  '/supranational/sdr',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const sdrs = await gruSupranationalService.getAllSdrAlternatives();
      res.json(sdrs);
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route POST /api/gru/supranational/sdr/:sdrId/update
 * @desc Update SDR value
 */
router.post(
  '/supranational/sdr/:sdrId/update',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const currentValue = await gruSupranationalService.updateSdrValue(
        req.params.sdrId
      );
      res.json({
        sdrId: req.params.sdrId,
        currentValue: currentValue.toString(),
        status: 'updated',
      });
    } catch (error) {
      return next(error);
    }
  }
);

// ============================================================================
// Volume II: Supranational Reserve Framework Routes
// ============================================================================

/**
 * @route POST /api/gru/reserve-pool
 * @desc Create a new reserve pool
 */
router.post(
  '/reserve-pool',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const result = await gruReservePoolService.createReservePool(req.body);
      res.json(result);
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route GET /api/gru/reserve-pool/:poolId
 * @desc Get reserve pool by ID
 */
router.get(
  '/reserve-pool/:poolId',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const pool = await gruReservePoolService.getReservePool(
        req.params.poolId
      );
      if (!pool) {
        return res.status(404).json({ error: 'Reserve pool not found' });
      }
      res.json(pool);
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route GET /api/gru/reserve-pool
 * @desc Get all reserve pools
 */
router.get('/reserve-pool', zeroTrustAuthMiddleware, async (req, res, next) => {
  try {
    const pools = await gruReservePoolService.getAllReservePools(
      req.query.poolType as any,
      req.query.entityId as string
    );
    res.json(pools);
  } catch (error) {
      return next(error);
  }
});

/**
 * @route POST /api/gru/reserve-pool/allocate
 * @desc Allocate reserves to a pool
 */
router.post(
  '/reserve-pool/allocate',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const allocationId = await gruReservePoolService.allocateReserves(
        req.body
      );
      res.json({ allocationId, status: 'allocated' });
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route POST /api/gru/reserve-pool/withdraw
 * @desc Withdraw reserves from a pool
 */
router.post(
  '/reserve-pool/withdraw',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const withdrawalId = await gruReservePoolService.withdrawReserves(
        req.body
      );
      res.json({ withdrawalId, status: 'pending' });
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route POST /api/gru/reserve-pool/withdraw/:withdrawalId/approve
 * @desc Approve withdrawal
 */
router.post(
  '/reserve-pool/withdraw/:withdrawalId/approve',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      await gruReservePoolService.approveWithdrawal(
        req.params.withdrawalId,
        req.body.approverId
      );
      res.json({ withdrawalId: req.params.withdrawalId, status: 'approved' });
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route POST /api/gru/reserve-pool/mutualize
 * @desc Mutualize liquidity between pools
 */
router.post(
  '/reserve-pool/mutualize',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const { sourcePoolId, targetPoolId, amount } = req.body;
      const mutualizationId = await gruReservePoolService.mutualizeLiquidity(
        sourcePoolId,
        targetPoolId,
        amount
      );
      res.json({ mutualizationId, status: 'completed' });
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route POST /api/gru/reserve-pool/crisis-intervention
 * @desc Regional crisis intervention
 */
router.post(
  '/reserve-pool/crisis-intervention',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const { poolId, amount, crisisType } = req.body;
      const allocationId = await gruReservePoolService.crisisIntervention(
        poolId,
        amount,
        crisisType
      );
      res.json({ allocationId, status: 'intervention_initiated' });
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route POST /api/gru/sdr/initialize
 * @desc Initialize SDR_GRU instrument
 */
router.post(
  '/sdr/initialize',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const sdrId = await gruSdrService.initializeSdr(req.body.fxBasket);
      res.json({ sdrId, status: 'initialized' });
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route GET /api/gru/sdr/:sdrId
 * @desc Get SDR instrument
 */
router.get('/sdr/:sdrId', zeroTrustAuthMiddleware, async (req, res, next) => {
  try {
    const sdr = await gruSdrService.getSdr(req.params.sdrId);
    if (!sdr) {
      return res.status(404).json({ error: 'SDR instrument not found' });
    }
    res.json(sdr);
  } catch (error) {
      return next(error);
  }
});

/**
 * @route POST /api/gru/sdr/:sdrId/calculate
 * @desc Calculate SDR valuation
 */
router.post(
  '/sdr/:sdrId/calculate',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const result = await gruSdrService.calculateValuation(
        req.params.sdrId
      );
      res.json(result);
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route GET /api/gru/sdr/:sdrId/value
 * @desc Get current SDR value
 */
router.get(
  '/sdr/:sdrId/value',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const value = await gruSdrService.getCurrentValue(req.params.sdrId);
      res.json({ sdrId: req.params.sdrId, currentValue: value.toString() });
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route POST /api/gru/sdr/convert-to
 * @desc Convert currency to SDR_GRU
 */
router.post(
  '/sdr/convert-to',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const result = await gruSdrService.convertToSdr(req.body);
      res.json(result);
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route POST /api/gru/sdr/convert-from
 * @desc Convert SDR_GRU to currency
 */
router.post(
  '/sdr/convert-from',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const { sdrId, sdrAmount, targetCurrency } = req.body;
      const result = await gruSdrService.convertFromSdr(
        sdrId,
        sdrAmount,
        targetCurrency
      );
      res.json(result);
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route POST /api/gru/supranational/issue
 * @desc Issue supranational GRU
 */
router.post(
  '/supranational/issue',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const result =
        await gruSupranationalIssuanceService.issueSupranationalGru(
          req.body
        );
      res.json(result);
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route POST /api/gru/supranational/eligibility
 * @desc Check eligibility for supranational issuance
 */
router.post(
  '/supranational/eligibility',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const { entityId, sovereignBankId, reserveClass } = req.body;
      const result = await gruSupranationalIssuanceService.checkEligibility(
        entityId,
        sovereignBankId,
        reserveClass
      );
      res.json(result);
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route GET /api/gru/supranational/issuances
 * @desc Get supranational issuances
 */
router.get(
  '/supranational/issuances',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const issuances =
        await gruSupranationalIssuanceService.getSupranationalIssuances(
          req.query.entityId as string,
          req.query.reserveClass as any
        );
      res.json(issuances);
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route POST /api/gru/legal-instruments/grc
 * @desc Issue GRU Reserve Certificate (GRC)
 */
router.post(
  '/legal-instruments/grc',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const result = await gruLegalInstrumentsService.issueGrc(req.body);
      res.json(result);
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route POST /api/gru/legal-instruments/grb
 * @desc Issue GRU Reserve Bond (GRB)
 */
router.post(
  '/legal-instruments/grb',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const result = await gruLegalInstrumentsService.issueGrb(req.body);
      res.json(result);
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route POST /api/gru/legal-instruments/gsdr
 * @desc Issue GRU SDR Instrument (GSDR)
 */
router.post(
  '/legal-instruments/gsdr',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const result = await gruLegalInstrumentsService.issueGsdr(req.body);
      res.json(result);
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route GET /api/gru/legal-instruments/grc/:certificateId
 * @desc Get GRC by ID
 */
router.get(
  '/legal-instruments/grc/:certificateId',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const grc = await gruLegalInstrumentsService.getGrc(
        req.params.certificateId
      );
      if (!grc) {
        return res.status(404).json({ error: 'GRC not found' });
      }
      res.json(grc);
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route GET /api/gru/legal-instruments/grb/:bondId
 * @desc Get GRB by ID
 */
router.get(
  '/legal-instruments/grb/:bondId',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const grb = await gruLegalInstrumentsService.getGrb(req.params.bondId);
      if (!grb) {
        return res.status(404).json({ error: 'GRB not found' });
      }
      res.json(grb);
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route POST /api/gru/legal-instruments/grb/:bondId/coupon/:couponId/pay
 * @desc Pay bond coupon
 */
router.post(
  '/legal-instruments/grb/:bondId/coupon/:couponId/pay',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      await gruLegalInstrumentsService.payBondCoupon(req.params.couponId);
      res.json({ couponId: req.params.couponId, status: 'paid' });
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route POST /api/gru/settlement/supranational
 * @desc Execute supranational settlement
 */
router.post(
  '/settlement/supranational',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const result =
        await gruSupranationalSettlementService.executeSupraGruSettlement(
          req.body
        );
      res.json(result);
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route GET /api/gru/settlement/supranational/:settlementId
 * @desc Get supranational settlement
 */
router.get(
  '/settlement/supranational/:settlementId',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const settlement =
        await gruSupranationalSettlementService.getSettlement(
          req.params.settlementId
        );
      if (!settlement) {
        return res.status(404).json({ error: 'Settlement not found' });
      }
      res.json(settlement);
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route POST /api/gru/settlement/supranational/:settlementId/reconcile
 * @desc Cross-chain reconciliation
 */
router.post(
  '/settlement/supranational/:settlementId/reconcile',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      await gruSupranationalSettlementService.reconcileCrossChain(
        req.params.settlementId
      );
      res.json({
        settlementId: req.params.settlementId,
        status: 'reconciled',
      });
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route POST /api/gru/sare/evaluate-exposure
 * @desc Evaluate sovereign exposure
 */
router.post(
  '/sare/evaluate-exposure',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const { sovereignBankId } = req.body;
      const result =
        await gruSareIntegrationService.evaluateSovereignExposure(
          sovereignBankId
        );
      res.json(result);
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route POST /api/gru/sare/reserve-adequacy
 * @desc Calculate reserve adequacy
 */
router.post(
  '/sare/reserve-adequacy',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const { entityId, sovereignBankId } = req.body;
      const result = await gruSareIntegrationService.calculateReserveAdequacy(
        entityId,
        sovereignBankId
      );
      res.json(result);
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route GET /api/gru/sare/monitor-pools
 * @desc Monitor reserve pools
 */
router.get(
  '/sare/monitor-pools',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const results = await gruSareIntegrationService.monitorReservePools();
      res.json(results);
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route POST /api/gru/ari/ensure-compliance
 * @desc Ensure compliance
 */
router.post(
  '/ari/ensure-compliance',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const { poolId, entityId } = req.body;
      const result = await gruAriIntegrationService.ensureCompliance(
        poolId,
        entityId
      );
      res.json(result);
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route POST /api/gru/ari/check-smia
 * @desc Check SMIA compliance
 */
router.post(
  '/ari/check-smia',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const { entityId, sovereignBankId } = req.body;
      const compliant = await gruAriIntegrationService.checkSmiaCompliance(
        entityId,
        sovereignBankId
      );
      res.json({ compliant, entityId, sovereignBankId });
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route POST /api/gru/ari/check-ilie
 * @desc Check ILIE compliance
 */
router.post(
  '/ari/check-ilie',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const { sovereignBankId } = req.body;
      const compliant = await gruAriIntegrationService.checkIlieCompliance(
        sovereignBankId
      );
      res.json({ compliant, sovereignBankId });
    } catch (error) {
      return next(error);
    }
  }
);

// ============================================================================
// GRU Institutional Whitepaper: Regulatory Classification Routes
// ============================================================================

/**
 * @route POST /api/gru/regulatory/classify
 * @desc Classify entity for GRU access
 */
router.post(
  '/regulatory/classify',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const result = await gruRegulatoryClassificationService.classifyEntity(req.body);
      res.json(result);
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route GET /api/gru/regulatory/class/:class
 * @desc Get entities by regulatory class
 */
router.get(
  '/regulatory/class/:class',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const entities = await gruRegulatoryClassificationService.getEntitiesByClass(
        req.params.class as any
      );
      res.json(entities);
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route GET /api/gru/regulatory/eligibility/:entityId
 * @desc Check eligibility
 */
router.get(
  '/regulatory/eligibility/:entityId',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const eligibility = await gruRegulatoryClassificationService.checkEligibility(
        req.params.entityId
      );
      res.json(eligibility);
    } catch (error) {
      return next(error);
    }
  }
);

// ============================================================================
// GRU Institutional Whitepaper: Supranational Governance Routes
// ============================================================================

/**
 * @route POST /api/gru/governance/application
 * @desc Submit issuance application
 */
router.post(
  '/governance/application',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const result = await gruSupranationalGovernanceService.submitApplication(req.body);
      res.json(result);
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route GET /api/gru/governance/application/:applicationId
 * @desc Get application status
 */
router.get(
  '/governance/application/:applicationId',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const status = await gruSupranationalGovernanceService.getApplicationStatus(
        req.params.applicationId
      );
      res.json(status);
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route POST /api/gru/governance/application/:applicationId/approve
 * @desc Approve application
 */
router.post(
  '/governance/application/:applicationId/approve',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      await gruSupranationalGovernanceService.approveApplication(
        req.params.applicationId
      );
      res.json({ applicationId: req.params.applicationId, status: 'approved' });
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route GET /api/gru/governance/pathway/:issuanceId
 * @desc Get issuance pathway status
 */
router.get(
  '/governance/pathway/:issuanceId',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const pathway = await gruSupranationalGovernanceService.getIssuancePathway(
        req.params.issuanceId
      );
      res.json(pathway);
    } catch (error) {
      return next(error);
    }
  }
);

// ============================================================================
// GRU Institutional Whitepaper: Legal Framework Routes
// ============================================================================

/**
 * @route GET /api/gru/legal/compliance/:issuanceId
 * @desc Get compliance status
 */
router.get(
  '/legal/compliance/:issuanceId',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const compliance = await gruLegalFrameworkService.getComplianceStatus(
        req.params.issuanceId
      );
      res.json(compliance);
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route POST /api/gru/legal/verify
 * @desc Verify legal framework compliance
 */
router.post(
  '/legal/verify',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const results = await gruLegalFrameworkService.verifyCompliance(req.body);
      res.json(results);
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route GET /api/gru/legal/frameworks
 * @desc List all legal frameworks
 */
router.get(
  '/legal/frameworks',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const frameworks = await gruLegalFrameworkService.getAllFrameworks();
      res.json(frameworks);
    } catch (error) {
      return next(error);
    }
  }
);

// ============================================================================
// GRU Institutional Whitepaper: Settlement Pipeline Routes
// ============================================================================

/**
 * @route POST /api/gru/settlement/pipeline
 * @desc Initiate settlement pipeline
 */
router.post(
  '/settlement/pipeline',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const result = await gruSettlementPipelineService.initiatePipeline(req.body);
      res.json(result);
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route GET /api/gru/settlement/pipeline/:pipelineId
 * @desc Get pipeline status
 */
router.get(
  '/settlement/pipeline/:pipelineId',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const status = await gruSettlementPipelineService.getPipelineStatus(
        req.params.pipelineId
      );
      res.json(status);
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route POST /api/gru/settlement/gas
 * @desc GAS atomic settlement
 */
router.post(
  '/settlement/gas',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const { pipelineId, ...request } = req.body;
      const settlementId = await gruSettlementPipelineService.executeGasSettlement(
        pipelineId,
        request
      );
      res.json({ settlementId, pipelineId, status: 'settled' });
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route POST /api/gru/settlement/omega
 * @desc Ω-Layer finality
 */
router.post(
  '/settlement/omega',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const { pipelineId } = req.body;
      const finalityId = await gruSettlementPipelineService.executeOmegaFinality(
        pipelineId
      );
      res.json({ finalityId, pipelineId, status: 'finalized' });
    } catch (error) {
      return next(error);
    }
  }
);

// ============================================================================
// GRU Institutional Whitepaper: Transparency Routes
// ============================================================================

/**
 * @route GET /api/gru/transparency/price-fixing
 * @desc Get daily price fixings
 */
router.get(
  '/transparency/price-fixing',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const date = req.query.date ? new Date(req.query.date as string) : undefined;
      const result = await gruTransparencyService.generateDailyPriceFixing(date);
      res.json(result);
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route GET /api/gru/transparency/liquidity-report
 * @desc Get liquidity reports
 */
router.get(
  '/transparency/liquidity-report',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const date = req.query.date ? new Date(req.query.date as string) : undefined;
      const result = await gruTransparencyService.generateLiquidityReport(date);
      res.json(result);
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route GET /api/gru/transparency/bond-health
 * @desc Get bond health metrics
 */
router.get(
  '/transparency/bond-health',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const date = req.query.date ? new Date(req.query.date as string) : undefined;
      const result = await gruTransparencyService.generateBondHealthMetrics(date);
      res.json(result);
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route GET /api/gru/transparency/stress-tests
 * @desc Get stress test results
 */
router.get(
  '/transparency/stress-tests',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const limit = parseInt(req.query.limit as string) || 10;
      const results = await gruTransparencyService.getStressTestResults(limit);
      res.json(results);
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route GET /api/gru/transparency/omega-proofs
 * @desc Get Ω-Layer settlement proofs
 */
router.get(
  '/transparency/omega-proofs',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const limit = parseInt(req.query.limit as string) || 100;
      const proofs = await gruTransparencyService.getOmegaLayerProofs(limit);
      res.json(proofs);
    } catch (error) {
      return next(error);
    }
  }
);

// ============================================================================
// GRU Institutional Whitepaper: Adoption Routes
// ============================================================================

/**
 * @route POST /api/gru/adoption/initiate
 * @desc Initiate adoption process
 */
router.post(
  '/adoption/initiate',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const result = await gruAdoptionService.initiateAdoption(req.body);
      res.json(result);
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route GET /api/gru/adoption/:adoptionId
 * @desc Get adoption status
 */
router.get(
  '/adoption/:adoptionId',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const status = await gruAdoptionService.getAdoptionStatus(
        req.params.adoptionId
      );
      res.json(status);
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route POST /api/gru/adoption/:adoptionId/phase/:phase
 * @desc Advance to next phase
 */
router.post(
  '/adoption/:adoptionId/phase/:phase',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      await gruAdoptionService.advanceToPhase(
        req.params.adoptionId,
        req.params.phase as any
      );
      res.json({
        adoptionId: req.params.adoptionId,
        phase: req.params.phase,
        status: 'advanced',
      });
    } catch (error) {
      return next(error);
    }
  }
);

// ============================================================================
// GRU Institutional Whitepaper: Regulatory Classification Routes
// ============================================================================

/**
 * @route POST /api/gru/regulatory/classify
 * @desc Classify entity for GRU access
 */
router.post(
  '/regulatory/classify',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const result = await gruRegulatoryClassificationService.classifyEntity(req.body);
      res.json(result);
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route GET /api/gru/regulatory/class/:class
 * @desc Get entities by regulatory class
 */
router.get(
  '/regulatory/class/:class',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const entities = await gruRegulatoryClassificationService.getEntitiesByClass(
        req.params.class as any
      );
      res.json(entities);
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route GET /api/gru/regulatory/eligibility/:entityId
 * @desc Check eligibility
 */
router.get(
  '/regulatory/eligibility/:entityId',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const eligibility = await gruRegulatoryClassificationService.checkEligibility(
        req.params.entityId
      );
      res.json(eligibility);
    } catch (error) {
      return next(error);
    }
  }
);

// ============================================================================
// GRU Institutional Whitepaper: Supranational Governance Routes
// ============================================================================

/**
 * @route POST /api/gru/governance/application
 * @desc Submit issuance application
 */
router.post(
  '/governance/application',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const result = await gruSupranationalGovernanceService.submitApplication(req.body);
      res.json(result);
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route GET /api/gru/governance/application/:applicationId
 * @desc Get application status
 */
router.get(
  '/governance/application/:applicationId',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const status = await gruSupranationalGovernanceService.getApplicationStatus(
        req.params.applicationId
      );
      res.json(status);
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route POST /api/gru/governance/application/:applicationId/approve
 * @desc Approve application
 */
router.post(
  '/governance/application/:applicationId/approve',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      await gruSupranationalGovernanceService.approveApplication(
        req.params.applicationId
      );
      res.json({ applicationId: req.params.applicationId, status: 'approved' });
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route GET /api/gru/governance/pathway/:issuanceId
 * @desc Get issuance pathway status
 */
router.get(
  '/governance/pathway/:issuanceId',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const pathway = await gruSupranationalGovernanceService.getIssuancePathway(
        req.params.issuanceId
      );
      res.json(pathway);
    } catch (error) {
      return next(error);
    }
  }
);

// ============================================================================
// GRU Institutional Whitepaper: Legal Framework Routes
// ============================================================================

/**
 * @route GET /api/gru/legal/compliance/:issuanceId
 * @desc Get compliance status
 */
router.get(
  '/legal/compliance/:issuanceId',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const compliance = await gruLegalFrameworkService.getComplianceStatus(
        req.params.issuanceId
      );
      res.json(compliance);
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route POST /api/gru/legal/verify
 * @desc Verify legal framework compliance
 */
router.post(
  '/legal/verify',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const results = await gruLegalFrameworkService.verifyCompliance(req.body);
      res.json(results);
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route GET /api/gru/legal/frameworks
 * @desc List all legal frameworks
 */
router.get(
  '/legal/frameworks',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const frameworks = await gruLegalFrameworkService.getAllFrameworks();
      res.json(frameworks);
    } catch (error) {
      return next(error);
    }
  }
);

// ============================================================================
// GRU Institutional Whitepaper: Settlement Pipeline Routes
// ============================================================================

/**
 * @route POST /api/gru/settlement/pipeline
 * @desc Initiate settlement pipeline
 */
router.post(
  '/settlement/pipeline',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const result = await gruSettlementPipelineService.initiatePipeline(req.body);
      res.json(result);
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route GET /api/gru/settlement/pipeline/:pipelineId
 * @desc Get pipeline status
 */
router.get(
  '/settlement/pipeline/:pipelineId',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const status = await gruSettlementPipelineService.getPipelineStatus(
        req.params.pipelineId
      );
      res.json(status);
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route POST /api/gru/settlement/gas
 * @desc GAS atomic settlement
 */
router.post(
  '/settlement/gas',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const { pipelineId, ...request } = req.body;
      const settlementId = await gruSettlementPipelineService.executeGasSettlement(
        pipelineId,
        request
      );
      res.json({ settlementId, pipelineId, status: 'settled' });
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route POST /api/gru/settlement/omega
 * @desc Ω-Layer finality
 */
router.post(
  '/settlement/omega',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const { pipelineId } = req.body;
      const finalityId = await gruSettlementPipelineService.executeOmegaFinality(
        pipelineId
      );
      res.json({ finalityId, pipelineId, status: 'finalized' });
    } catch (error) {
      return next(error);
    }
  }
);

// ============================================================================
// GRU Institutional Whitepaper: Transparency Routes
// ============================================================================

/**
 * @route GET /api/gru/transparency/price-fixing
 * @desc Get daily price fixings
 */
router.get(
  '/transparency/price-fixing',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const date = req.query.date ? new Date(req.query.date as string) : undefined;
      const result = await gruTransparencyService.generateDailyPriceFixing(date);
      res.json(result);
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route GET /api/gru/transparency/liquidity-report
 * @desc Get liquidity reports
 */
router.get(
  '/transparency/liquidity-report',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const date = req.query.date ? new Date(req.query.date as string) : undefined;
      const result = await gruTransparencyService.generateLiquidityReport(date);
      res.json(result);
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route GET /api/gru/transparency/bond-health
 * @desc Get bond health metrics
 */
router.get(
  '/transparency/bond-health',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const date = req.query.date ? new Date(req.query.date as string) : undefined;
      const result = await gruTransparencyService.generateBondHealthMetrics(date);
      res.json(result);
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route GET /api/gru/transparency/stress-tests
 * @desc Get stress test results
 */
router.get(
  '/transparency/stress-tests',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const limit = parseInt(req.query.limit as string) || 10;
      const results = await gruTransparencyService.getStressTestResults(limit);
      res.json(results);
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route GET /api/gru/transparency/omega-proofs
 * @desc Get Ω-Layer settlement proofs
 */
router.get(
  '/transparency/omega-proofs',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const limit = parseInt(req.query.limit as string) || 100;
      const proofs = await gruTransparencyService.getOmegaLayerProofs(limit);
      res.json(proofs);
    } catch (error) {
      return next(error);
    }
  }
);

// ============================================================================
// GRU Institutional Whitepaper: Adoption Routes
// ============================================================================

/**
 * @route POST /api/gru/adoption/initiate
 * @desc Initiate adoption process
 */
router.post(
  '/adoption/initiate',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const result = await gruAdoptionService.initiateAdoption(req.body);
      res.json(result);
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route GET /api/gru/adoption/:adoptionId
 * @desc Get adoption status
 */
router.get(
  '/adoption/:adoptionId',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const status = await gruAdoptionService.getAdoptionStatus(
        req.params.adoptionId
      );
      res.json(status);
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route POST /api/gru/adoption/:adoptionId/phase/:phase
 * @desc Advance to next phase
 */
router.post(
  '/adoption/:adoptionId/phase/:phase',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      await gruAdoptionService.advanceToPhase(
        req.params.adoptionId,
        req.params.phase as any
      );
      res.json({
        adoptionId: req.params.adoptionId,
        phase: req.params.phase,
        status: 'advanced',
      });
    } catch (error) {
      return next(error);
    }
  }
);

export default router;

