const express = require('express');
const router = express.Router();
const { all, get } = require('../utils/db');
const { success } = require('../utils/response');

// 🔒 匿名可读配置需脱敏：过滤含 密钥/key/secret/mch/merchant/sign/private/cert/appid秘钥 的敏感字段
const SENSITIVE_KEY_RE = /(key|secret|mch|merchant|sign|private|cert|token|api[_-]?key|app[_-]?(id|secret)|password|passwd)/i;
function publicSafe(map) {
  const out = {};
  for (const k of Object.keys(map)) {
    if (SENSITIVE_KEY_RE.test(k)) continue; // 跳过敏感字段
    out[k] = map[k];
  }
  return out;
}

// 公开配置
router.get('/public', (req, res) => {
  const configs = all("SELECT key,value FROM system_config WHERE group_name IN ('base','payment','share','ai')");
  const map = {};
  configs.forEach(c => map[c.key] = c.value);
  return res.json(success(publicSafe(map)));
});

// 支付配置（匿名只返回脱敏后的非敏感项）
router.get('/payment', (req, res) => {
  const configs = all("SELECT key,value FROM system_config WHERE group_name='payment'");
  const map = {};
  configs.forEach(c => map[c.key] = c.value);
  return res.json(success(publicSafe(map)));
});

// 分享配置
router.get('/share', (req, res) => {
  const configs = all("SELECT key,value FROM system_config WHERE group_name='share'");
  const map = {};
  configs.forEach(c => map[c.key] = c.value);
  return res.json(success(map));
});

module.exports = router;
