import { Request, Response } from 'express';
import { ArbitrageHeatmapService } from '../../domains/Arbitrage/ArbitrageHeatmapService';
import { ArbitrageService } from '../../domains/Arbitrage/ArbitrageService';
import { SupplyChainService } from '../../services/SupplyChainService';
import { logger } from '../../utils/logger';

/**
 * [BIZ_ARB_01] & [UX_BI_05] 套利中心控制器
 */
export class ArbitrageController {
  /**
   * 获取多维套利空间实时热力分析 (Heatmap)
   * GET /api/v1/arbitrage/heatmap
   */
  static async getHeatmap(req: Request, res: Response) {
    const tenantId = req.headers['x-tenant-id'] as string;

    if (!tenantId) {
      return res.status(400).json({ success: false, error: 'x-tenant-id header is required' });
    }

    try {
      const heatmap = await ArbitrageHeatmapService.getHeatmapData(tenantId);
      const trend = await ArbitrageHeatmapService.getTrendHeatmap(tenantId, 14);

      return res.json({
        success: true,
        data: {
          heatmap,
          trend
        }
      });
    } catch (err: any) {
      logger.error(`[ArbitrageController] Get heatmap failed: ${err.message}`);
      return res.status(500).json({ success: false, error: 'Internal server error' });
    }
  }

  /**
   * [CORE_AI_50] 多模态 AGI 视觉寻源
   * POST /api/v1/arbitrage/visual-sourcing
   */
  static async visualSourcing(req: Request, res: Response) {
    const { imageUrl } = req.body;

    if (!imageUrl) {
      return res.status(400).json({ success: false, error: 'imageUrl is required' });
    }

    try {
      const results = await SupplyChainService.visualSourcing(imageUrl);
      return res.json({ success: true, data: results });
    } catch (err: any) {
      return res.status(500).json({ success: false, error: err.message });
    }
  }

  /**
   * 初始化套利表 (通常在启动时由 DomainBootstrap 处理)
   */
  static async init(req: Request, res: Response) {
    try {
      await ArbitrageService.initTable();
      return res.json({ success: true, message: 'Arbitrage tables initialized' });
    } catch (err: any) {
      return res.status(500).json({ success: false, error: err.message });
    }
  }
}
