import { Request, Response } from 'express';
import db from '../../config/database';
import { FeatureGovernanceService } from '../../core/governance/FeatureGovernanceService';
import { RedTeamingService } from '../../core/governance/RedTeamingService';
import { UnifiedTaskService } from '../../services/UnifiedTaskService';

export class GovernanceController {
  /**
   * 获取待办任务列表 (FE_INBOX_01)
   */
  static async getPendingTasks(req: Request, res: Response) {
    try {
      const { tenantId } = (req as any).traceContext;
      const tasks = await UnifiedTaskService.getPendingTasks(tenantId);
      res.json({ success: true, data: tasks });
    } catch (err: any) {
      res.status(500).json({ success: false, error: err.message });
    }
  }

  /**
   * 认领任务
   */
  static async claimTask(req: Request, res: Response) {
    try {
      const { taskId, userId } = req.body;
      if (!taskId || !userId) return res.status(400).json({ success: false, error: 'Missing taskId or userId' });
      
      const success = await UnifiedTaskService.claimTask(taskId, userId);
      res.json({ success });
    } catch (err: any) {
      res.status(500).json({ success: false, error: err.message });
    }
  }

  /**
   * 完成任务
   */
  static async completeTask(req: Request, res: Response) {
    try {
      const { taskId, metadata } = req.body;
      if (!taskId) return res.status(400).json({ success: false, error: 'Missing taskId' });
      
      await UnifiedTaskService.completeTask(taskId, metadata);
      res.json({ success: true });
    } catch (err: any) {
      res.status(500).json({ success: false, error: err.message });
    }
  }
  /**
   * 运行自动化安全测试 (BIZ_AUDIT_RED_TEAMING)
   */
  static async runRedTeamTests(req: Request, res: Response) {
    const result = await RedTeamingService.runAutomatedTests();
    res.json({ success: true, data: result });
  }

  /**
   * 获取安全合规报告
   */
  static async getSecurityReport(req: Request, res: Response) {
    const report = await RedTeamingService.getSecurityReport();
    res.json({ success: true, data: report });
  }

  /**
   * 获取所有功能开关 (支持租户级透视)
   */
  static async getFeatureFlags(req: Request, res: Response) {
    const { tenantId } = req.query;
    const flags = await FeatureGovernanceService.getAllFeatures(tenantId as string);
    res.json({ success: true, data: flags });
  }

  /**
   * 注册或更新功能描述 (Dynamic Registration)
   */
  static async registerFeature(req: Request, res: Response) {
    const { featureKey, isEnabled, description, scope, metadata } = req.body;
    if (!featureKey) return res.status(400).json({ success: false, error: 'Missing featureKey' });

    await FeatureGovernanceService.registerFeature({
      featureKey,
      isEnabled: isEnabled ?? true,
      description: description || '',
      scope: scope || 'GLOBAL',
      metadata
    });
    res.json({ success: true, message: `Feature ${featureKey} registered/updated` });
  }

  /**
   * 切换全局功能开关
   */
  static async toggleFeature(req: Request, res: Response) {
    const { featureKey, isEnabled } = req.body;
    if (!featureKey) return res.status(400).json({ success: false, error: 'Missing featureKey' });

    await FeatureGovernanceService.toggleGlobalFeature(featureKey, isEnabled);
    res.json({ success: true, message: `Feature ${featureKey} global status changed to ${isEnabled}` });
  }

  /**
   * 设置租户级覆盖配置
   */
  static async setTenantOverride(req: Request, res: Response) {
    const { tenantId, featureKey, isEnabled } = req.body;
    if (!tenantId || !featureKey) {
      return res.status(400).json({ success: false, error: 'Missing tenantId or featureKey' });
    }

    await FeatureGovernanceService.setTenantOverride(tenantId, featureKey, isEnabled);
    res.json({ success: true, message: `Tenant ${tenantId} override set for ${featureKey}: ${isEnabled}` });
  }

  /**
   * 获取租户级覆盖配置
   */
  static async getTenantOverrides(req: Request, res: Response) {
    const { tenantId } = req.params;
    const overrides = await db('cf_tenant_feature_flags').where({ tenant_id: tenantId });
    res.json({ success: true, data: overrides });
  }
}
