// GRU Operations API Routes
// GRU Banking Operations Manual - API Endpoints

import { Router } from 'express';
import { gruAccountService } from './gru-account.service';
import { gruDailyOperationsService } from './gru-daily-operations.service';
import { gruReconciliationService } from './gru-reconciliation.service';
import { gruLiquidityManagementService } from './gru-liquidity-management.service';
import { gruRiskManagementService } from './gru-risk-management.service';
import { gruSettlementOperationsService } from './gru-settlement-operations.service';
import { gruComplianceReportingService } from './gru-compliance-reporting.service';
import { gruSecurityOperationsService } from './gru-security-operations.service';
import { gruInteroperabilityService } from './gru-interoperability.service';
import { zeroTrustAuthMiddleware } from '@/integration/api-gateway/middleware/auth.middleware';

const router = Router();

// ============================================================================
// GRU Account Management Endpoints
// ============================================================================

/**
 * @route POST /api/gru/accounts
 * @desc Create GRU account
 */
router.post(
  '/accounts',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const result = await gruAccountService.createGruAccount(req.body);
      res.json(result);
    } catch (error) {
      return next(error);
    }
  }
);

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

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

// ============================================================================
// Daily Operations Endpoints
// ============================================================================

/**
 * @route POST /api/gru/operations/daily/initialize
 * @desc Initialize daily operations
 */
router.post(
  '/operations/daily/initialize',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const result = await gruDailyOperationsService.initializeDailyOperations(req.body);
      res.json(result);
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route POST /api/gru/operations/daily/closeout
 * @desc Execute end-of-day closeout
 */
router.post(
  '/operations/daily/closeout',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const result = await gruDailyOperationsService.executeEndOfDayCloseout(req.body);
      res.json({ closeoutId: result });
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route POST /api/gru/operations/transaction
 * @desc Process transaction
 */
router.post(
  '/operations/transaction',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const result = await gruDailyOperationsService.processTransaction(req.body);
      res.json({ transactionId: result });
    } catch (error) {
      return next(error);
    }
  }
);

// ============================================================================
// Reconciliation Endpoints
// ============================================================================

/**
 * @route POST /api/gru/reconciliation/gas
 * @desc GAS reconciliation
 */
router.post(
  '/reconciliation/gas',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const result = await gruReconciliationService.reconcileGAS(req.body);
      res.json(result);
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route POST /api/gru/reconciliation/quantum-drift
 * @desc Quantum drift correction
 */
router.post(
  '/reconciliation/quantum-drift',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      await gruReconciliationService.correctQuantumDrift(req.body);
      res.json({ status: 'completed' });
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route POST /api/gru/reconciliation/account
 * @desc Reconcile account
 */
router.post(
  '/reconciliation/account',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const result = await gruReconciliationService.reconcileAccount(
        req.body.accountId,
        req.body.reconciliationDate ? new Date(req.body.reconciliationDate) : undefined
      );
      res.json(result);
    } catch (error) {
      return next(error);
    }
  }
);

// ============================================================================
// Liquidity Management Endpoints
// ============================================================================

/**
 * @route GET /api/gru/liquidity/monitoring
 * @desc Get liquidity monitoring
 */
router.get(
  '/liquidity/monitoring',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const result = await gruLiquidityManagementService.monitorXAUAnchor(req.query);
      res.json(result);
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route POST /api/gru/liquidity/predictive
 * @desc Run predictive liquidity models
 */
router.post(
  '/liquidity/predictive',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const result = await gruLiquidityManagementService.runPredictiveModels(req.body);
      res.json({ predictionId: result });
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route POST /api/gru/liquidity/demand
 * @desc Evaluate liquidity demand
 */
router.post(
  '/liquidity/demand',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const result = await gruLiquidityManagementService.evaluateLiquidityDemand(req.body);
      res.json({ demandId: result });
    } catch (error) {
      return next(error);
    }
  }
);

// ============================================================================
// Risk Management Endpoints
// ============================================================================

/**
 * @route POST /api/gru/risk/daily-controls
 * @desc Run daily risk controls
 */
router.post(
  '/risk/daily-controls',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const result = await gruRiskManagementService.runDailyRiskControls(req.body);
      res.json(result);
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route GET /api/gru/risk/screening
 * @desc Get volatility screening results
 */
router.get(
  '/risk/screening',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const result = await gruRiskManagementService.screenVolatility(req.query);
      res.json(result);
    } catch (error) {
      return next(error);
    }
  }
);

// ============================================================================
// Settlement Operations Endpoints
// ============================================================================

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

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

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

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

// ============================================================================
// Compliance & Reporting Endpoints
// ============================================================================

/**
 * @route GET /api/gru/compliance/daily-reports
 * @desc Get daily compliance reports
 */
router.get(
  '/compliance/daily-reports',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const result = await gruComplianceReportingService.generateDailyReports(req.query);
      res.json(result);
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route GET /api/gru/compliance/monthly-reports
 * @desc Get monthly compliance reports
 */
router.get(
  '/compliance/monthly-reports',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const result = await gruComplianceReportingService.generateMonthlyReports(req.query);
      res.json(result);
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route GET /api/gru/compliance/annual-reports
 * @desc Get annual compliance reports
 */
router.get(
  '/compliance/annual-reports',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const result = await gruComplianceReportingService.generateAnnualReports(req.query);
      res.json(result);
    } catch (error) {
      return next(error);
    }
  }
);

// ============================================================================
// Security Operations Endpoints
// ============================================================================

/**
 * @route POST /api/gru/security/verify-qek
 * @desc Verify quantum envelope keys
 */
router.post(
  '/security/verify-qek',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const result = await gruSecurityOperationsService.verifyQuantumEnvelopeKeys(req.body);
      res.json(result);
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route POST /api/gru/security/detect-threats
 * @desc Detect threats
 */
router.post(
  '/security/detect-threats',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const result = await gruSecurityOperationsService.detectThreats(req.body);
      res.json(result);
    } catch (error) {
      return next(error);
    }
  }
);

// ============================================================================
// Interoperability Endpoints
// ============================================================================

/**
 * @route POST /api/gru/interoperability/convert
 * @desc Convert GRU to other assets
 */
router.post(
  '/interoperability/convert',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const { sourceCurrency, targetCurrency, sourceAmount } = req.body;

      let result;
      if (targetCurrency === 'XAU') {
        result = await gruInteroperabilityService.convertGRUToXAU({
          sourceAmount,
          sourceCurrency,
          targetCurrency,
        });
      } else if (targetCurrency === 'CBDC') {
        result = await gruInteroperabilityService.convertGRUToCBDC({
          sourceAmount,
          sourceCurrency,
          targetCurrency,
        });
      } else if (targetCurrency === 'SSR') {
        result = await gruInteroperabilityService.convertGRUToSSR({
          sourceAmount,
          sourceCurrency,
          targetCurrency,
        });
      } else {
        return res.status(400).json({ error: 'Unsupported target currency' });
      }

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

/**
 * @route POST /api/gru/interoperability/route/swift
 * @desc Route to SWIFT
 */
router.post(
  '/interoperability/route/swift',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const result = await gruInteroperabilityService.routeToSWIFT(req.body);
      res.json(result);
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route POST /api/gru/interoperability/route/metaverse
 * @desc Route to Metaverse
 */
router.post(
  '/interoperability/route/metaverse',
  zeroTrustAuthMiddleware,
  async (req, res, next) => {
    try {
      const result = await gruInteroperabilityService.routeToMetaverse(req.body);
      res.json(result);
    } catch (error) {
      return next(error);
    }
  }
);

export default router;

