const express = require('express');
const router = express.Router();
const { get, run, all } = require('../utils/db');
const { isFeatureEnabled } = require('../lib/license');
const { authAdmin } = require('../middleware/auth');

// ========== 功能门控：多终端管理仅在完整版可用 ==========
router.use((req, res, next) => {
  if (!isFeatureEnabled('multi_terminal')) {
    return res.json({ code: 403, message: '当前版本不支持多终端管理功能', data: null });
  }
  // 写操作需管理员（防匿名改配置/触发推送）
  if (req.method !== 'GET') {
    return authAdmin(req, res, next);
  }
  next();
});

router.get('/config', (req, res) => {
  const { terminal, group } = req.query;
  const row = get("SELECT value FROM system_config WHERE `key`=?", [`terminal_${terminal}_${group}`]);
  res.json({ code: 0, data: row ? JSON.parse(row.value) : {} });
});

router.post('/config', (req, res) => {
  const { terminal, group, data } = req.body;
  const key = `terminal_${terminal}_${group}`;
  const val = JSON.stringify(data);
  const exist = get("SELECT id FROM system_config WHERE `key`=?", [key]);
  exist ? run("UPDATE system_config SET `value`=? WHERE `key`=?", [val, key]) : run("INSERT INTO system_config(`key`,`value`) VALUES(?,?)", [key, val]);
  res.json({ code: 0, message: '配置已保存' });
});

module.exports = router;

// 推送菜单
router.post('/push-menu', (req, res) => {
  // 模拟推送成功
  res.json({ code: 0, message: '菜单已推送到微信服务器' });
});

// 全部同步
router.post('/sync-all', (req, res) => {
  res.json({ code: 0, message: '同步任务已触发' });
});

// 同步日志
router.get('/logs', (req, res) => {
  const logs = [];
  res.json({ code: 0, data: logs });
});
