import express from 'express';
import { fetchMarketOverview, fetchMarketDetail, fetchKlineData, fetchMarketHotspots, fetchRiskAlerts } from '../services/marketService';
import { logger } from '../utils/logger';

const router = express.Router();

// 获取市场概览
router.get('/overview', async (req, res) => {
  try {
    logger.info('start 获取市场概览');
    const data = await fetchMarketOverview();
    logger.info('end 获取市场概览');
    res.status(200).json({ success: true, data });
  } catch (error) {
    logger.error('获取市场概览失败:', error);
    res.status(500).json({ success: false, message: '获取市场概览失败' });
  }
});

// 获取品种详情
router.get('/detail/:symbol', async (req, res) => {
  try {
    logger.info(`start 获取合约${req.params.symbol}详情`);
    const { symbol } = req.params;
    const data = await fetchMarketDetail(symbol);
    logger.info(`end 获取合约${symbol}详情`);
    res.status(200).json({ success: true, data });
  } catch (error) {
    logger.error(`获取合约${req.params.symbol}详情失败:`, error);
    res.status(500).json({ success: false, message: '获取品种详情失败' });
  }
});

// 获取K线数据
router.get('/klines/:symbol', async (req, res) => {
  try {
    logger.info(`start 获取合约${req.params.symbol}K线数据`);
    const { symbol } = req.params;
    const { period = '1H' } = req.query;
    const data = await fetchKlineData(symbol, period as string);
    logger.info(`end 获取合约${symbol}K线数据`);
    res.status(200).json({ success: true, data });
  } catch (error) {
    logger.error(`获取合约${req.params.symbol}K线数据失败:`, error);
    res.status(500).json({ success: false, message: '获取K线数据失败' });
  }
});

// 获取市场热点
router.get('/hotspots', async (req, res) => {
  try {
    logger.info('start 获取市场热点');
    const data = await fetchMarketHotspots();
    logger.info('end 获取市场热点');
    res.status(200).json({ success: true, data });
  } catch (error) {
    logger.error('获取市场热点失败:', error);
    res.status(500).json({ success: false, message: '获取市场热点失败' });
  }
});

// 获取风险预警
router.get('/alerts', async (req, res) => {
  try {
    logger.info('start 获取风险预警');
    const data = await fetchRiskAlerts();
    logger.info('end 获取风险预警');
    res.status(200).json({ success: true, data });
  } catch (error) {
    logger.error('获取风险预警失败:', error);
    res.status(500).json({ success: false, message: '获取风险预警失败' });
  }
});

export default router;