import { Router, Request, Response } from 'express';
import { cacheMiddleware } from '../middleware/cache';
import { RouteDecisionTreeService } from '../../services/route-decision-tree';

const router = Router();
const treeService = new RouteDecisionTreeService();

/**
 * GET /api/v1/routes/tree
 * Query:
 * - chainId
 * - tokenIn
 * - tokenOut (optional)
 * - amountIn (optional)
 * - destinationChainId (optional)
 */
router.get('/routes/tree', cacheMiddleware(10 * 1000), async (req: Request, res: Response) => {
  try {
    const chainId = parseInt(req.query.chainId as string, 10);
    const tokenIn = req.query.tokenIn as string;
    const tokenOut = req.query.tokenOut as string | undefined;
    const amountIn = req.query.amountIn as string | undefined;
    const destinationChainIdRaw = req.query.destinationChainId as string | undefined;
    const destinationChainId = destinationChainIdRaw ? parseInt(destinationChainIdRaw, 10) : undefined;

    if (!chainId || !tokenIn) {
      return res.status(400).json({
        error: 'chainId and tokenIn are required',
      });
    }

    const tree = await treeService.build({
      chainId,
      tokenIn,
      tokenOut,
      amountIn,
      destinationChainId,
    });

    res.json(tree);
  } catch (error) {
    // eslint-disable-next-line no-console -- route error logging
    console.error('Route tree error:', error);
    res.status(500).json({
      error: error instanceof Error ? error.message : 'Internal server error',
    });
  }
});

/**
 * GET /api/v1/routes/depth
 * Convenience endpoint for the most relevant depth metrics.
 */
router.get('/routes/depth', cacheMiddleware(10 * 1000), async (req: Request, res: Response) => {
  try {
    const chainId = parseInt(req.query.chainId as string, 10);
    const tokenIn = req.query.tokenIn as string;
    const tokenOut = req.query.tokenOut as string | undefined;
    const amountIn = req.query.amountIn as string | undefined;
    const destinationChainIdRaw = req.query.destinationChainId as string | undefined;
    const destinationChainId = destinationChainIdRaw ? parseInt(destinationChainIdRaw, 10) : undefined;

    if (!chainId || !tokenIn) {
      return res.status(400).json({
        error: 'chainId and tokenIn are required',
      });
    }

    const tree = await treeService.build({
      chainId,
      tokenIn,
      tokenOut,
      amountIn,
      destinationChainId,
    });

    res.json({
      generatedAt: tree.generatedAt,
      decision: tree.decision,
      source: tree.source,
      destination: tree.destination,
      pools: tree.pools,
      missingQuoteTokenPools: tree.missingQuoteTokenPools,
    });
  } catch (error) {
    // eslint-disable-next-line no-console -- route error logging
    console.error('Route depth error:', error);
    res.status(500).json({
      error: error instanceof Error ? error.message : 'Internal server error',
    });
  }
});

export default router;
