import { Router, Request, Response } from 'express';
import { getNetworks, getConfigByChain, API_VERSION } from '../../config/networks';
import { cacheMiddleware } from '../middleware/cache';
import { fetchRemoteJson } from '../utils/fetch-remote-json';
import { logger } from '../../utils/logger';

const router: Router = Router();

/**
 * GET /api/v1/networks
 * Full EIP-3085 chain params for wallet_addEthereumChain (Chain 138, 1, 651940).
 * If NETWORKS_JSON_URL is set (e.g. GitHub raw URL), fetches and returns that JSON; otherwise uses built-in networks.
 */
router.get('/networks', cacheMiddleware(5 * 60 * 1000), async (req: Request, res: Response) => {
  try {
    const networksJsonUrl = process.env.NETWORKS_JSON_URL?.trim();
    if (networksJsonUrl) {
      try {
        const data = (await fetchRemoteJson(networksJsonUrl)) as { version?: string; networks?: unknown[] };
        return res.json({
          version: data.version ?? API_VERSION,
          networks: data.networks ?? [],
        });
      } catch (err) {
        logger.error('NETWORKS_JSON_URL fetch failed, using built-in networks:', err);
      }
    }
    const networks = getNetworks();
    res.json({
      version: API_VERSION,
      networks,
    });
  } catch (error) {
    res.status(500).json({ error: 'Internal server error' });
  }
});

/**
 * GET /api/v1/config
 * Oracles (and optional config) per chain. Query: chainId (optional).
 * If chainId provided, returns config for that chain only.
 */
router.get('/config', cacheMiddleware(5 * 60 * 1000), async (req: Request, res: Response) => {
  try {
    const chainIdParam = req.query.chainId as string | undefined;
    const networks = getNetworks();
    if (chainIdParam) {
      const chainId = parseInt(chainIdParam, 10);
      const config = getConfigByChain(chainId);
      if (!config) {
        return res.status(404).json({ error: 'Chain not found', chainId });
      }
      return res.json({ version: API_VERSION, chainId, ...config });
    }
    const chains = networks.map((n) => ({
      chainId: n.chainIdDecimal,
      oracles: n.oracles,
    }));
    res.json({ version: API_VERSION, chains });
  } catch (error) {
    res.status(500).json({ error: 'Internal server error' });
  }
});

export default router;
