/**
 * [BE-AIAUTO-004] 自动化等级管理API路由
 * 提供AI决策自动化配置的CRUD接口
 */

import { Router } from 'express';
import { AutoExecutionConfigService, AutomationLevel, DecisionModule } from '../../services/AutoExecutionConfigService';
import { validateAutoExecution, requireAutoExecute, requireReviewPermission, requireLevelChangePermission } from '../middleware/AutoExecutionMiddleware';
import { logger } from '../../utils/logger';

const router = Router();

/**
 * GET /api/auto-execution/configs
 * 获取所有模块配置
 */
router.get('/configs', async (req, res) => {
  try {
    const tenantId = (req as any).user?.tenantId || req.query.tenant_id;
    const shopId = req.query.shop_id as string;

    if (!tenantId) {
      return res.status(400).json({
        success: false,
        error: 'MISSING_TENANT_ID',
        message: '缺少租户ID',
      });
    }

    const configs = await AutoExecutionConfigService.getAllConfigs(tenantId, shopId);
    
    res.json({
      success: true,
      data: configs,
    });
  } catch (error) {
    logger.error('[AutoExecution] Get configs error:', error);
    res.status(500).json({
      success: false,
      error: 'GET_CONFIGS_ERROR',
      message: '获取配置失败',
    });
  }
});

/**
 * GET /api/auto-execution/config/:module
 * 获取单个模块配置
 */
router.get('/config/:module', async (req, res) => {
  try {
    const tenantId = (req as any).user?.tenantId || req.query.tenant_id;
    const shopId = req.query.shop_id as string;
    const module = req.params.module as DecisionModule;

    if (!tenantId || !shopId) {
      return res.status(400).json({
        success: false,
        error: 'MISSING_REQUIRED_FIELDS',
        message: '缺少必要字段: tenant_id, shop_id',
      });
    }

    const userId = (req as any).user?.id || 'SYSTEM';
    const config = await AutoExecutionConfigService.getOrCreateConfig(tenantId, shopId, module, userId);
    
    res.json({
      success: true,
      data: config,
    });
  } catch (error) {
    logger.error('[AutoExecution] Get config error:', error);
    res.status(500).json({
      success: false,
      error: 'GET_CONFIG_ERROR',
      message: '获取配置失败',
    });
  }
});

/**
 * PUT /api/auto-execution/config/:configId
 * 更新模块配置
 */
router.put('/config/:configId', async (req, res) => {
  try {
    const configId = req.params.configId;
    const userId = (req as any).user?.id || 'SYSTEM';
    const updates = req.body;

    const config = await AutoExecutionConfigService.updateConfig(configId, updates, userId);
    
    res.json({
      success: true,
      data: config,
      message: '配置更新成功',
    });
  } catch (error) {
    logger.error('[AutoExecution] Update config error:', error);
    res.status(500).json({
      success: false,
      error: 'UPDATE_CONFIG_ERROR',
      message: '更新配置失败',
    });
  }
});

/**
 * POST /api/auto-execution/validate
 * 校验执行请求
 */
router.post('/validate', validateAutoExecution, (req, res) => {
  const validation = req.autoExecutionValidation;
  
  res.json({
    success: true,
    data: validation,
  });
});

/**
 * POST /api/auto-execution/execute
 * 执行AI决策（需要通过校验）
 */
router.post('/execute', validateAutoExecution, requireAutoExecute, async (req, res) => {
  try {
    const body = req.body;
    const validation = req.autoExecutionValidation;
    
    res.json({
      success: true,
      message: '决策执行成功',
      data: {
        decision_id: `DEC-${Date.now()}`,
        action: validation?.required_action,
        executed_at: new Date(),
      },
    });
  } catch (error) {
    logger.error('[AutoExecution] Execute error:', error);
    res.status(500).json({
      success: false,
      error: 'EXECUTE_ERROR',
      message: '执行失败',
    });
  }
});

/**
 * POST /api/auto-execution/review
 * 审核待执行的决策
 */
router.post('/review', requireReviewPermission, async (req, res) => {
  try {
    const { decision_id, action, comment } = req.body;
    const userId = (req as any).user?.id;
    const userName = (req as any).user?.name || 'Unknown';

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

    const validActions = ['APPROVE', 'REJECT', 'MODIFY'];
    if (!validActions.includes(action)) {
      return res.status(400).json({
        success: false,
        error: 'INVALID_ACTION',
        message: `操作必须是: ${validActions.join(', ')}`,
      });
    }

    await AutoExecutionConfigService.recordExecution(
      (req as any).user?.tenantId,
      req.body.shop_id,
      req.body.module,
      action === 'APPROVE',
      req.body.confidence || 0.8,
      false
    );

    res.json({
      success: true,
      message: action === 'APPROVE' ? '决策已批准执行' : '决策已拒绝',
      data: {
        decision_id,
        action,
        reviewed_by: userName,
        reviewed_at: new Date(),
      },
    });
  } catch (error) {
    logger.error('[AutoExecution] Review error:', error);
    res.status(500).json({
      success: false,
      error: 'REVIEW_ERROR',
      message: '审核失败',
    });
  }
});

/**
 * POST /api/auto-execution/level/upgrade
 * 升级自动化等级
 */
router.post('/level/upgrade', requireLevelChangePermission, async (req, res) => {
  try {
    const { tenant_id, shop_id, module, target_level, reason } = req.body;
    const userId = (req as any).user?.id;

    if (!tenant_id || !shop_id || !module || !target_level || !reason) {
      return res.status(400).json({
        success: false,
        error: 'MISSING_REQUIRED_FIELDS',
        message: '缺少必要字段',
      });
    }

    const evolution = await AutoExecutionConfigService.upgradeLevel(
      tenant_id,
      shop_id,
      module,
      target_level,
      reason,
      userId
    );

    res.json({
      success: true,
      message: `自动化等级已升级至 ${target_level}`,
      data: evolution,
    });
  } catch (error) {
    logger.error('[AutoExecution] Upgrade level error:', error);
    const errorMessage = error instanceof Error ? error.message : '升级失败';
    res.status(400).json({
      success: false,
      error: 'UPGRADE_LEVEL_ERROR',
      message: errorMessage,
    });
  }
});

/**
 * POST /api/auto-execution/level/downgrade
 * 降级自动化等级
 */
router.post('/level/downgrade', requireLevelChangePermission, async (req, res) => {
  try {
    const { tenant_id, shop_id, module, target_level, reason } = req.body;
    const userId = (req as any).user?.id;

    if (!tenant_id || !shop_id || !module || !target_level || !reason) {
      return res.status(400).json({
        success: false,
        error: 'MISSING_REQUIRED_FIELDS',
        message: '缺少必要字段',
      });
    }

    const evolution = await AutoExecutionConfigService.downgradeLevel(
      tenant_id,
      shop_id,
      module,
      target_level,
      reason,
      userId
    );

    res.json({
      success: true,
      message: `自动化等级已降级至 ${target_level}`,
      data: evolution,
    });
  } catch (error) {
    logger.error('[AutoExecution] Downgrade level error:', error);
    const errorMessage = error instanceof Error ? error.message : '降级失败';
    res.status(400).json({
      success: false,
      error: 'DOWNGRADE_LEVEL_ERROR',
      message: errorMessage,
    });
  }
});

/**
 * GET /api/auto-execution/evolution-history
 * 获取等级演进历史
 */
router.get('/evolution-history', async (req, res) => {
  try {
    const tenantId = (req as any).user?.tenantId || req.query.tenant_id;
    const shopId = req.query.shop_id as string;
    const module = req.query.module as DecisionModule;

    if (!tenantId) {
      return res.status(400).json({
        success: false,
        error: 'MISSING_TENANT_ID',
        message: '缺少租户ID',
      });
    }

    const history = await AutoExecutionConfigService.getEvolutionHistory(tenantId, shopId, module);
    
    res.json({
      success: true,
      data: history,
    });
  } catch (error) {
    logger.error('[AutoExecution] Get evolution history error:', error);
    res.status(500).json({
      success: false,
      error: 'GET_EVOLUTION_HISTORY_ERROR',
      message: '获取演进历史失败',
    });
  }
});

/**
 * GET /api/auto-execution/level-capabilities
 * 获取等级能力说明
 */
router.get('/level-capabilities', (req, res) => {
  const capabilities = AutoExecutionConfigService.getLevelCapabilities();
  
  res.json({
    success: true,
    data: capabilities,
  });
});

/**
 * GET /api/auto-execution/module-defaults
 * 获取模块默认配置
 */
router.get('/module-defaults', (req, res) => {
  const defaults = AutoExecutionConfigService.getModuleDefaults();
  
  res.json({
    success: true,
    data: defaults,
  });
});

/**
 * POST /api/auto-execution/init-tables
 * 初始化数据库表（仅管理员）
 */
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 AutoExecutionConfigService.initTables();
    
    res.json({
      success: true,
      message: '数据库表初始化成功',
    });
  } catch (error) {
    logger.error('[AutoExecution] Init tables error:', error);
    res.status(500).json({
      success: false,
      error: 'INIT_TABLES_ERROR',
      message: '初始化数据库表失败',
    });
  }
});

export default router;
