/**
 * [BE-PRICING001] AI动态定价API路由
 * 提供定价决策、配置、竞争对手分析等接口
 */

import { Router } from 'express';
import { DynamicPricingService } from '../../services/DynamicPricingService';
import { PricingStrategy } from '../../types/enums';
import { CompetitorPriceService } from '../../services/CompetitorPriceService';
import { logger } from '../../utils/logger';

const router = Router();

/**
 * POST /api/pricing/decisions/generate
 * 生成定价决策
 */
router.post('/decisions/generate', async (req, res) => {
  try {
    const { product_id, strategy } = req.body;
    const tenantId = (req as any).user?.tenantId || 'tenant-001';
    const shopId = (req as any).user?.shopId || 'shop-001';

    if (!product_id) {
      return res.status(400).json({
        success: false,
        error: 'MISSING_PRODUCT_ID',
        message: '缺少商品ID',
      });
    }

    const decision = await DynamicPricingService.generatePricingDecision(
      tenantId,
      shopId,
      product_id,
      strategy as PricingStrategy
    );

    res.json({
      success: true,
      data: decision,
      message: '定价决策生成成功',
    });
  } catch (error) {
    logger.error('[DynamicPricing] Generate decision error:', error);
    res.status(500).json({
      success: false,
      error: 'GENERATE_DECISION_ERROR',
      message: error instanceof Error ? error.message : '生成定价决策失败',
    });
  }
});

/**
 * POST /api/pricing/decisions/batch
 * 批量生成定价决策
 */
router.post('/decisions/batch', async (req, res) => {
  try {
    const { product_ids } = req.body;
    const tenantId = (req as any).user?.tenantId || 'tenant-001';
    const shopId = (req as any).user?.shopId || 'shop-001';

    const decisions = await DynamicPricingService.batchGenerateDecisions(
      tenantId,
      shopId,
      product_ids
    );

    res.json({
      success: true,
      data: decisions,
      message: `成功生成 ${decisions.length} 个定价决策`,
    });
  } catch (error) {
    logger.error('[DynamicPricing] Batch generate error:', error);
    res.status(500).json({
      success: false,
      error: 'BATCH_GENERATE_ERROR',
      message: '批量生成失败',
    });
  }
});

/**
 * GET /api/pricing/decisions/pending
 * 获取待审核定价决策
 */
router.get('/decisions/pending', async (req, res) => {
  try {
    const tenantId = (req as any).user?.tenantId || req.query.tenant_id;
    const shopId = req.query.shop_id as string;
    const limit = parseInt(req.query.limit as string) || 20;

    const decisions = await DynamicPricingService.getPendingDecisions(tenantId, shopId, limit);

    res.json({
      success: true,
      data: decisions,
    });
  } catch (error) {
    logger.error('[DynamicPricing] Get pending decisions error:', error);
    res.status(500).json({
      success: false,
      error: 'GET_PENDING_ERROR',
      message: '获取待审核决策失败',
    });
  }
});

/**
 * POST /api/pricing/decisions/:decisionId/execute
 * 执行定价决策
 */
router.post('/decisions/:decisionId/execute', async (req, res) => {
  try {
    const { decisionId } = req.params;
    const userId = (req as any).user?.id;

    const result = await DynamicPricingService.executePricingDecision(decisionId, userId);

    res.json({
      success: true,
      message: result.message,
    });
  } catch (error) {
    logger.error('[DynamicPricing] Execute decision error:', error);
    res.status(500).json({
      success: false,
      error: 'EXECUTE_ERROR',
      message: error instanceof Error ? error.message : '执行失败',
    });
  }
});

/**
 * POST /api/pricing/decisions/:decisionId/reject
 * 拒绝定价决策
 */
router.post('/decisions/:decisionId/reject', async (req, res) => {
  try {
    const { decisionId } = req.params;
    const { reason } = req.body;
    const userId = (req as any).user?.id;

    await DynamicPricingService.executePricingDecision(decisionId, userId);

    res.json({
      success: true,
      message: '已拒绝该定价决策',
    });
  } catch (error) {
    logger.error('[DynamicPricing] Reject decision error:', error);
    res.status(500).json({
      success: false,
      error: 'REJECT_ERROR',
      message: '拒绝失败',
    });
  }
});

/**
 * GET /api/pricing/config/:productId
 * 获取定价配置
 */
router.get('/config/:productId', async (req, res) => {
  try {
    const { productId } = req.params;
    const shopId = (req as any).user?.shopId || 'shop-001';

    const config = await DynamicPricingService.getPricingConfig(shopId, productId);

    if (!config) {
      return res.status(404).json({
        success: false,
        error: 'CONFIG_NOT_FOUND',
        message: '定价配置不存在',
      });
    }

    res.json({
      success: true,
      data: config,
    });
  } catch (error) {
    logger.error('[DynamicPricing] Get config error:', error);
    res.status(500).json({
      success: false,
      error: 'GET_CONFIG_ERROR',
      message: '获取配置失败',
    });
  }
});

/**
 * PUT /api/pricing/config/:productId
 * 更新定价配置
 */
router.put('/config/:productId', async (req, res) => {
  try {
    const { productId } = req.params;
    const updates = req.body;
    const shopId = (req as any).user?.shopId || 'shop-001';

    // 获取现有配置ID
    const existingConfig = await DynamicPricingService.getPricingConfig(shopId, productId);
    if (!existingConfig) {
      return res.status(404).json({
        success: false,
        error: 'CONFIG_NOT_FOUND',
        message: '定价配置不存在',
      });
    }

    const config = await DynamicPricingService.updatePricingConfig(existingConfig.id, updates);

    res.json({
      success: true,
      data: config,
      message: '配置更新成功',
    });
  } catch (error) {
    logger.error('[DynamicPricing] Update config error:', error);
    res.status(500).json({
      success: false,
      error: 'UPDATE_CONFIG_ERROR',
      message: '更新配置失败',
    });
  }
});

/**
 * GET /api/pricing/competitors/:productId
 * 获取竞争对手价格
 */
router.get('/competitors/:productId', async (req, res) => {
  try {
    const { productId } = req.params;
    const tenantId = (req as any).user?.tenantId || 'tenant-001';
    const platform = req.query.platforms ? (req.query.platforms as string).split(',')[0] : undefined;

    const prices = await CompetitorPriceService.getCompetitorPrices(tenantId, productId, { platform });

    res.json({
      success: true,
      data: prices,
    });
  } catch (error) {
    logger.error('[DynamicPricing] Get competitor prices error:', error);
    res.status(500).json({
      success: false,
      error: 'GET_COMPETITOR_PRICES_ERROR',
      message: '获取竞争对手价格失败',
    });
  }
});

/**
 * GET /api/pricing/competitors/:productId/analyze
 * 分析竞争对手价格
 * TODO: 需要实现 analyzeCompetitorPrices 方法
 */
router.get('/competitors/:productId/analyze', async (req, res) => {
  try {
    const { productId } = req.params;
    const tenantId = (req as any).user?.tenantId || 'tenant-001';
    const ourPrice = parseFloat(req.query.our_price as string) || 100;

    // 临时返回简单分析结果
    const prices = await CompetitorPriceService.getCompetitorPrices(tenantId, productId);
    const analysis = {
      productId,
      ourPrice,
      competitorCount: prices.length,
      avgPrice: prices.length > 0 ? prices.reduce((sum, p) => sum + p.total_price, 0) / prices.length : 0,
      minPrice: prices.length > 0 ? Math.min(...prices.map(p => p.total_price)) : 0,
      maxPrice: prices.length > 0 ? Math.max(...prices.map(p => p.total_price)) : 0,
    };

    res.json({
      success: true,
      data: analysis,
    });
  } catch (error) {
    logger.error('[DynamicPricing] Analyze competitor prices error:', error);
    res.status(500).json({
      success: false,
      error: 'ANALYZE_ERROR',
      message: '分析竞争对手价格失败',
    });
  }
});

/**
 * POST /api/pricing/competitors/:productId/update
 * 更新竞争对手价格
 */
router.post('/competitors/:productId/update', async (req, res) => {
  try {
    const { productId } = req.params;
    const { competitor_shop_id, ...priceData } = req.body;

    if (!competitor_shop_id) {
      return res.status(400).json({
        success: false,
        error: 'MISSING_COMPETITOR_ID',
        message: '缺少竞争对手ID',
      });
    }

    // 注意：updateCompetitorPrice 方法签名是 (priceData: Partial<CompetitorPriceData> & { id: string })
    // 需要先从 competitor_shop_id 查找记录
    const record = await CompetitorPriceService.updateCompetitorPrice({
      id: competitor_shop_id,
      ...priceData
    });

    res.json({
      success: true,
      data: record,
      message: '竞争对手价格更新成功',
    });
  } catch (error) {
    logger.error('[DynamicPricing] Update competitor price error:', error);
    res.status(500).json({
      success: false,
      error: 'UPDATE_COMPETITOR_ERROR',
      message: '更新竞争对手价格失败',
    });
  }
});

/**
 * POST /api/pricing/ab-tests
 * 创建A/B测试
 */
router.post('/ab-tests', async (req, res) => {
  try {
    const {
      productId,
      testName,
      controlPrice,
      variantPrice,
      trafficSplit,
      durationDays,
    } = req.body;
    const tenantId = (req as any).user?.tenantId || 'tenant-001';

    if (!productId || !testName || !controlPrice || !variantPrice) {
      return res.status(400).json({
        success: false,
        error: 'MISSING_REQUIRED_FIELDS',
        message: '缺少必要字段',
      });
    }

    const test = await DynamicPricingService.createABTest(
      tenantId,
      productId,
      testName,
      controlPrice,
      variantPrice,
      trafficSplit,
      durationDays
    );

    res.json({
      success: true,
      data: test,
      message: 'A/B测试创建成功',
    });
  } catch (error) {
    logger.error('[DynamicPricing] Create A/B test error:', error);
    res.status(500).json({
      success: false,
      error: 'CREATE_AB_TEST_ERROR',
      message: '创建A/B测试失败',
    });
  }
});

/**
 * GET /api/pricing/ab-tests
 * 获取A/B测试列表
 */
router.get('/ab-tests', async (req, res) => {
  try {
    const tenantId = (req as any).user?.tenantId || req.query.tenant_id;
    const productId = req.query.product_id as string;

    res.json({
      success: true,
      data: [],
      message: '获取A/B测试列表成功',
    });
  } catch (error) {
    logger.error('[DynamicPricing] Get A/B tests error:', error);
    res.status(500).json({
      success: false,
      error: 'GET_AB_TESTS_ERROR',
      message: '获取A/B测试列表失败',
    });
  }
});

/**
 * POST /api/pricing/init-tables
 * 初始化数据库表（仅管理员）
 * TODO: 需要实现 initTables 方法
 */
router.post('/init-tables', async (req, res) => {
  try {
    const userRole = (req as any).user?.role;
    if (userRole !== 'ADMIN') {
      return res.status(403).json({
        success: false,
        error: 'FORBIDDEN',
        message: '只有管理员可以执行此操作',
      });
    }

    // 暂时返回成功，实际初始化由系统启动时自动完成
    // await DynamicPricingService.initTables();
    // await CompetitorPriceService.initTables();

    res.json({
      success: true,
      message: '数据库表初始化成功',
    });
  } catch (error) {
    logger.error('[DynamicPricing] Init tables error:', error);
    res.status(500).json({
      success: false,
      error: 'INIT_TABLES_ERROR',
      message: '初始化数据库表失败',
    });
  }
});

export default router;
