import { Router } from 'express';
import { body } from 'express-validator';
import { SystemService } from '../services/SystemService.js';
import { authenticate, authorize } from '../middleware/auth.js';
import { asyncHandler } from '../middleware/error.js';
import { validateRequest } from '../middleware/validate.js';

const router = Router();
const systemService = new SystemService();

// 获取系统配置（公开）
router.get(
  '/config',
  asyncHandler(async (_req, res) => {
    const config = await systemService.getPublicConfig();
    res.json({ success: true, data: config });
  })
);

// 更新系统配置（需要管理员权限）
router.put(
  '/config',
  authenticate,
  authorize('admin'),
  [
    body('allowRegistration').optional().isBoolean(),
    body('defaultUserRole').optional().isIn(['admin', 'editor', 'operator']),
    validateRequest,
  ],
  asyncHandler(async (req, res) => {
    await systemService.updateConfig(req.body);
    res.json({ success: true, message: '配置已更新' });
  })
);

// 获取系统状态（需要管理员权限）
router.get(
  '/status',
  authenticate,
  authorize('admin'),
  asyncHandler(async (_req, res) => {
    const status = await systemService.getSystemStatus();
    res.json({ success: true, data: status });
  })
);

export default router;
