import { Router, Request, Response } from 'express';
import StrategyService from '../../services/StrategyService';
import { StrategyRecommendationService } from '../../services/StrategyRecommendationService';
import { logger } from '../../utils/logger';

const router = Router();

router.get('/strategies', async (req: Request, res: Response) => {
  try {
    const { category, isActive, isFeatured, limit, offset } = req.query;

    const result = await StrategyService.getAllStrategies({
      category: category as string,
      isActive: isActive === 'true' ? true : isActive === 'false' ? false : undefined,
      isFeatured: isFeatured === 'true' ? true : isFeatured === 'false' ? false : undefined,
      limit: limit ? parseInt(limit as string) : undefined,
      offset: offset ? parseInt(offset as string) : undefined
    });

    res.json({
      success: true,
      data: result.strategies,
      total: result.total
    });
  } catch (error) {
    logger.error('[StrategyRoutes] Error fetching strategies:', error);
    res.status(500).json({
      success: false,
      message: 'Failed to fetch strategies'
    });
  }
});

router.get('/strategies/featured', async (req: Request, res: Response) => {
  try {
    const limit = req.query.limit ? parseInt(req.query.limit as string) : 5;
    const strategies = await StrategyService.getFeaturedStrategies(limit);

    res.json({
      success: true,
      data: strategies
    });
  } catch (error) {
    logger.error('[StrategyRoutes] Error fetching featured strategies:', error);
    res.status(500).json({
      success: false,
      message: 'Failed to fetch featured strategies'
    });
  }
});

router.get('/strategies/:id', async (req: Request, res: Response) => {
  try {
    const id = req.params.id as string;
    const strategy = await StrategyService.getStrategyById(id);

    if (!strategy) {
      return res.status(404).json({
        success: false,
        message: 'Strategy not found'
      });
    }

    res.json({
      success: true,
      data: strategy
    });
  } catch (error) {
    logger.error('[StrategyRoutes] Error fetching strategy:', error);
    res.status(500).json({
      success: false,
      message: 'Failed to fetch strategy'
    });
  }
});

router.get('/strategies/:id/similar', async (req: Request, res: Response) => {
  try {
    const id = req.params.id as string;
    const recommendationService = StrategyRecommendationService.getInstance();
    const strategies = await recommendationService.getSimilarStrategies(id);

    res.json({
      success: true,
      data: strategies
    });
  } catch (error) {
    logger.error('[StrategyRoutes] Error fetching similar strategies:', error);
    res.status(500).json({
      success: false,
      message: 'Failed to fetch similar strategies'
    });
  }
});

router.post('/strategies/:id/activate', async (req: Request, res: Response) => {
  try {
    const id = req.params.id as string;
    const tenantId = (req as any).user?.tenantId || 'default-tenant';
    const { config } = req.body;

    const result = await StrategyService.activateStrategy({
      strategyId: id,
      tenantId,
      config
    });

    res.json({
      success: true,
      data: result,
      message: 'Strategy activated successfully'
    });
  } catch (error) {
    logger.error('[StrategyRoutes] Error activating strategy:', error);
    res.status(500).json({
      success: false,
      message: 'Failed to activate strategy'
    });
  }
});

router.post('/strategies/:id/pause', async (req: Request, res: Response) => {
  try {
    const id = req.params.id as string;
    const tenantId = (req as any).user?.tenantId || 'default-tenant';

    await StrategyService.pauseStrategy(id, tenantId);

    res.json({
      success: true,
      message: 'Strategy paused successfully'
    });
  } catch (error) {
    logger.error('[StrategyRoutes] Error pausing strategy:', error);
    res.status(500).json({
      success: false,
      message: 'Failed to pause strategy'
    });
  }
});

router.post('/strategies/:id/resume', async (req: Request, res: Response) => {
  try {
    const id = req.params.id as string;
    const tenantId = (req as any).user?.tenantId || 'default-tenant';

    await StrategyService.resumeStrategy(id, tenantId);

    res.json({
      success: true,
      message: 'Strategy resumed successfully'
    });
  } catch (error) {
    logger.error('[StrategyRoutes] Error resuming strategy:', error);
    res.status(500).json({
      success: false,
      message: 'Failed to resume strategy'
    });
  }
});

router.post('/strategies/:id/complete', async (req: Request, res: Response) => {
  try {
    const id = req.params.id as string;
    const tenantId = (req as any).user?.tenantId || 'default-tenant';
    const { roi, revenue } = req.body;

    await StrategyService.completeStrategy(id, tenantId, { roi, revenue });

    res.json({
      success: true,
      message: 'Strategy completed successfully'
    });
  } catch (error) {
    logger.error('[StrategyRoutes] Error completing strategy:', error);
    res.status(500).json({
      success: false,
      message: 'Failed to complete strategy'
    });
  }
});

router.get('/recommendations', async (req: Request, res: Response) => {
  try {
    const tenantId = (req as any).user?.tenantId || 'default-tenant';
    const category = req.query.category as string;

    // 使用单例模式获取服务实例
    const recommendationService = StrategyRecommendationService.getInstance();
    const recommendations = category
      ? await recommendationService.getCategoryRecommendations(category, '10')
      : await recommendationService.getPersonalizedRecommendations(tenantId);

    res.json({
      success: true,
      data: recommendations
    });
  } catch (error) {
    logger.error('[StrategyRoutes] Error fetching recommendations:', error);
    res.status(500).json({
      success: false,
      message: 'Failed to fetch recommendations'
    });
  }
});

export default router;
