import { Router, Request, Response } from 'express';
import { cacheMiddleware } from '../middleware/cache';
import {
  AggregatorRouteFilters,
  filterLiveAggregatorRoutes,
  getAggregatorRouteMatrixPath,
  loadAggregatorRouteMatrix,
} from '../../config/aggregator-route-matrix';

const router: Router = Router();

function parseFilters(req: Request): AggregatorRouteFilters {
  const fromChainId = req.query.fromChainId ? parseInt(String(req.query.fromChainId), 10) : undefined;
  const toChainId = req.query.toChainId ? parseInt(String(req.query.toChainId), 10) : undefined;

  return {
    family: req.query.family ? String(req.query.family) : undefined,
    fromChainId: Number.isFinite(fromChainId) ? fromChainId : undefined,
    toChainId: Number.isFinite(toChainId) ? toChainId : undefined,
    routeType: req.query.routeType ? String(req.query.routeType) : undefined,
    tokenIn: req.query.tokenIn ? String(req.query.tokenIn) : undefined,
    tokenOut: req.query.tokenOut ? String(req.query.tokenOut) : undefined,
  };
}

/**
 * GET /api/v1/routes/matrix
 * Returns the canonical aggregator route matrix from config/aggregator-route-matrix.json.
 */
router.get('/routes/matrix', cacheMiddleware(30 * 1000), (req: Request, res: Response) => {
  const matrix = loadAggregatorRouteMatrix();
  if (!matrix) {
    return res.status(503).json({
      error: 'Aggregator route matrix not available',
    });
  }

  const filters = parseFilters(req);
  const includeNonLive = String(req.query.includeNonLive ?? 'false').toLowerCase() === 'true';
  const liveRoutes = filterLiveAggregatorRoutes(
    [...matrix.liveSwapRoutes, ...matrix.liveBridgeRoutes],
    filters
  );

  return res.json({
    generatedAt: new Date().toISOString(),
    sourcePath: getAggregatorRouteMatrixPath(),
    version: matrix.version,
    updated: matrix.updated,
    filters,
    homeChainId: matrix.homeChainId,
    liveRoutes,
    blockedOrPlannedRoutes: includeNonLive ? matrix.blockedOrPlannedRoutes : undefined,
    counts: {
      liveSwapRoutes: matrix.liveSwapRoutes.length,
      liveBridgeRoutes: matrix.liveBridgeRoutes.length,
      blockedOrPlannedRoutes: matrix.blockedOrPlannedRoutes.length,
      filteredLiveRoutes: liveRoutes.length,
    },
  });
});

/**
 * GET /api/v1/routes/ingestion
 * Adapter-focused flat export of only live routes, filtered by family/chain/token when provided.
 */
router.get('/routes/ingestion', cacheMiddleware(30 * 1000), (req: Request, res: Response) => {
  const matrix = loadAggregatorRouteMatrix();
  if (!matrix) {
    return res.status(503).json({
      error: 'Aggregator route matrix not available',
    });
  }

  const filters = parseFilters(req);
  const liveRoutes = filterLiveAggregatorRoutes(
    [...matrix.liveSwapRoutes, ...matrix.liveBridgeRoutes],
    filters
  );

  return res.json({
    generatedAt: new Date().toISOString(),
    format: 'aggregator-ingestion-v1',
    version: matrix.version,
    updated: matrix.updated,
    filters,
    routes: liveRoutes,
  });
});

export default router;
