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';
import type { Request, Response, NextFunction } from 'express';

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

function isLoopbackRequest(req: Request): boolean {
  const ip = req.ip || '';
  return ip === '127.0.0.1'
    || ip === '::1'
    || ip.startsWith('::ffff:127.');
}

// 本地回环请求放行，否则需任一已登录用户（不要求管理员）
function requireAuthOrLoopback(req: Request, res: Response, next: NextFunction): void {
  if (isLoopbackRequest(req)) {
    next();
    return;
  }
  authenticate(req, res, next);
}

// 获取系统配置（公开）
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(
  '/publish-proxy',
  authenticate,
  authorize('admin'),
  asyncHandler(async (_req, res) => {
    const config = await systemService.getPublishProxyAdminConfig();
    res.json({ success: true, data: config });
  })
);

router.get(
  '/publish-proxy/cities',
  authenticate,
  asyncHandler(async (_req, res) => {
    const cities = await systemService.getPublishProxyCitiesFromApi();
    res.json({ success: true, data: { cities } });
  })
);

router.get(
  '/publish-proxy/regions',
  authenticate,
  asyncHandler(async (_req, res) => {
    const regions = await systemService.getPublishProxyRegionsFromCsv();
    res.json({ success: true, data: { regions } });
  })
);

router.put(
  '/publish-proxy',
  authenticate,
  authorize('admin'),
  [
    body('productKey').optional().isString(),
    body('signature').optional().isString(),
    validateRequest,
  ],
  asyncHandler(async (req, res) => {
    await systemService.updatePublishProxyAdminConfig(req.body);
    res.json({ success: true, message: '发布代理配置已更新' });
  })
);

router.get(
  '/python-service',
  requireAuthOrLoopback,
  asyncHandler(async (_req, res) => {
    const config = await systemService.getPythonServiceAdminConfig();
    res.json({ success: true, data: config });
  })
);

router.put(
  '/python-service',
  requireAuthOrLoopback,
  [
    body('url').optional().isString(),
    validateRequest,
  ],
  asyncHandler(async (req, res) => {
    await systemService.updatePythonServiceAdminConfig(req.body);
    res.json({ success: true, message: 'Python 服务配置已更新' });
  })
);

router.post(
  '/python-service/check',
  requireAuthOrLoopback,
  [
    body('url').optional().isString(),
    validateRequest,
  ],
  asyncHandler(async (req, res) => {
    const result = await systemService.checkPythonService(req.body.url);
    res.json({ success: true, data: result });
  })
);

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

export default router;
