import { Request, Response, NextFunction } from 'express';
import { TraceService } from '../../services/TraceService';

/**
 * [CORE_LOG_02] 全局操作流水线追踪控制器
 */
export class TraceController {
  /**
   * 获取特定 Trace 的流水线详情
   */
  static async getPipeline(req: Request, res: Response, next: NextFunction) {
    try {
      const { traceId } = req.params;
      const { tenantId } = (req as any).traceContext;

      const data = await TraceService.getPipelineByTraceId(traceId as string, tenantId as string);
      
      if (!data) {
        return res.status(404).json({ success: false, error: 'Trace not found' });
      }

      res.json({ success: true, data });
    } catch (err) {
      next(err);
    }
  }

  /**
   * 获取租户最近的自治活动列表
   */
  static async getActivities(req: Request, res: Response, next: NextFunction) {
    try {
      const { tenantId } = (req as any).traceContext;
      const limit = req.query.limit ? parseInt(req.query.limit as string) : 20;

      const data = await TraceService.getRecentActivities(tenantId as string, limit);
      res.json({ success: true, data });
    } catch (err) {
      next(err);
    }
  }

  /**
   * [CORE_TELE_01] 获取自愈遥测流
   */
  static async getTelemetry(req: Request, res: Response, next: NextFunction) {
    try {
      const { tenantId } = (req as any).traceContext;
      const limit = req.query.limit ? parseInt(req.query.limit as string) : 50;

      const data = await TraceService.getSelfHealingTelemetry(tenantId as string, limit);
      res.json({ success: true, data });
    } catch (err) {
      next(err);
    }
  }
}
