import { Request, Response } from 'express';
import { ReportService, ReportType } from '../../domains/Analytics/ReportService';
import { AnalyticsService } from '../../domains/Analytics/AnalyticsService';
import { OrderProfitService } from '../../domains/Finance/OrderProfitService';
import { logger } from '../../utils/logger';

export class ReportController {
  /**
   * [FE_FIN_01] 获取实时 P&L 穿透分析数据 (Profit Breakdown)
   */
  static async getProfitBreakdown(req: Request, res: Response) {
    try {
      const { tenantId } = (req as any).traceContext || req.query;
      if (!tenantId) return res.status(400).json({ success: false, error: 'tenantId is required' });

      const breakdown = await OrderProfitService.getGlobalProfitBreakdown(tenantId as string);
      res.json({ success: true, data: breakdown });
    } catch (err: any) {
      res.status(500).json({ success: false, error: err.message });
    }
  }

  /**
   * [CORE_GOV_03] 下钻到具体订单或套利任务的明细 (Traceability)
   */
  static async getDetailedEvidence(req: Request, res: Response) {
    const { traceId } = req.params;
    if (!traceId) {
      return res.status(400).json({ success: false, error: 'traceId is required' });
    }

    try {
      const data = await AnalyticsService.getDetailedEvidence(traceId as string);
      return res.json({ success: true, data });
    } catch (err: any) {
      logger.error(`[ReportController] Get evidence failed: ${err.message}`);
      return res.status(500).json({ success: false, error: 'Internal server error' });
    }
  }

  /**
   * 获取多维报表数据
   */
  static async getReport(req: Request, res: Response) {
    const tenantId = req.headers['x-tenant-id'] as string;
    const { type } = req.params;
    const filters = req.query;

    if (!tenantId || !type) {
      return res.status(400).json({ success: false, error: 'tenantId and report type are required' });
    }

    try {
      const data = await ReportService.getReportData(tenantId, type as ReportType, filters);
      return res.json({ success: true, data });
    } catch (err: any) {
      logger.error(`[ReportController] Get report failed: ${err.message}`);
      return res.status(500).json({ success: false, error: 'Internal server error' });
    }
  }
}
