/**
 * Unified exchange API routes - price, status
 */

import { Router, Request, Response, NextFunction } from 'express';
import { exchangeRegistryService } from './exchange-registry.service';
import { fxService } from '@/core/fx/fx.service';

const router = Router();

/**
 * GET /api/v1/exchange/price
 * Get market price for pair - uses registry fallback
 * Query: pair (e.g. BTC/USD), amount (optional)
 */
router.get('/price', async (req: Request, res: Response, next: NextFunction) => {
  try {
    const pair = req.query.pair as string;
    const amount = req.query.amount ? parseFloat(req.query.amount as string) : undefined;

    if (!pair || !pair.includes('/')) {
      return res.status(400).json({
        success: false,
        error: 'Missing or invalid pair (e.g. BTC/USD)',
        timestamp: new Date(),
      });
      return;
    }

    const price = await exchangeRegistryService.getPrice(pair, amount);
    if (!price) {
      const fallback = await fxService.getMarketPrice(pair, amount);
      return res.json({ success: true, data: { pair, price: fallback, source: 'fallback' }, timestamp: new Date() });
    }

    return res.json({ success: true, data: { pair, price }, timestamp: new Date() });
  } catch (err) {
    return next(err);
  }
});

/**
 * GET /api/v1/exchange/providers
 * List enabled exchange providers
 */
router.get('/providers', async (_req: Request, res: Response, next: NextFunction) => {
  try {
    await exchangeRegistryService.initialize();
    const providers = exchangeRegistryService.listProviders();
    return res.json({ success: true, data: providers, timestamp: new Date() });
  } catch (err) {
    return next(err);
  }
});

export default router;
