/**
 * 会员储值充值模块
 * ================
 * 包含充值套餐管理、充值订单、余额查询等接口
 * 付费版专属功能
 */

const express = require('express');
const router = express.Router();
const { get, run, all, transaction } = require('../utils/db');
const { success, fail, page } = require('../utils/response');
const { authUser } = require('../middleware/auth');
const { isPremium } = require('../lib/limits');

// [安全] 充值回调守卫：仅显式 ALLOW_RECHARGE_CALLBACK=1（测试）时允许无验签回调；生产默认禁用防白嫖余额
const ALLOW_RECHARGE_CALLBACK = process.env.ALLOW_RECHARGE_CALLBACK === '1';
function genNo() { return 'RC' + Date.now() + String(Math.floor(Math.random() * 900) + 100); }
function isAdmin(req) { return req.baseUrl && req.baseUrl.indexOf('/admin/') !== -1; }

// 套餐列表
router.get('/plans', (req, res) => {
  try {
    const list = isAdmin(req)
      ? all('SELECT * FROM recharge_plans ORDER BY sort ASC, id ASC')
      : all('SELECT * FROM recharge_plans WHERE status=1 ORDER BY sort ASC, id ASC');
    return res.json(success(list));
  } catch (e) { return res.json(fail('获取失败')); }
});

// 余额
router.get('/balance', authUser, (req, res) => {
  try {
    const u = get('SELECT balance, experience FROM users WHERE id=?', [req.userId]);
    return u ? res.json(success({ balance: u.balance || 0, experience: u.experience || 0 })) : res.json(fail('用户不存在'));
  } catch (e) { return res.json(fail('查询失败')); }
});

// 创建订单
router.post('/order', authUser, (req, res) => {
  try {
    if (!isPremium()) return res.json(fail('会员储值功能需付费版，升级后可解锁', 403));
    const { plan_id, payment_method } = req.body;
    if (!plan_id) return res.json(fail('请选择充值套餐'));
    if (!payment_method || !['wechat', 'alipay'].includes(payment_method)) return res.json(fail('请选择支付方式'));

    const plan = get('SELECT * FROM recharge_plans WHERE id=? AND status=1', [plan_id]);
    if (!plan) return res.json(fail('套餐不存在或已下架'));

    const no = genNo();
    transaction(() => {
      run('INSERT INTO recharge_orders(order_no,user_id,plan_id,amount,give_amount,give_points,status,payment_method) VALUES(?,?,?,?,?,?,?,?)',
        [no, req.userId, plan.id, plan.amount, plan.give_amount || 0, plan.give_points || 0, 'pending', payment_method]);
    });

    return res.json(success({
      order_no: no, amount: plan.amount, give_amount: plan.give_amount || 0,
      give_points: plan.give_points || 0, payment_method: payment_method,
      pay_url: '/api/payment/mock-pay?trade_no=' + no + '&order_no=' + no
    }, '订单创建成功，请完成支付'));
  } catch (e) { return res.json(fail('创建订单失败')); }
});

// 订单列表（用户或管理员）
router.get('/orders', authUser, (req, res) => {
  try {
    const p = Math.max(1, +req.query.page || 1);
    const ps = Math.min(100, Math.max(1, +req.query.pageSize || 20));

    if (isAdmin(req)) {
      let where = 'WHERE 1=1'; const params = [];
      if (req.query.status) { where += ' AND ro.status=?'; params.push(req.query.status); }
      if (req.query.keyword) {
        const kw = '%' + req.query.keyword + '%';
        where += ' AND (ro.order_no LIKE ? OR u.nickname LIKE ? OR u.phone LIKE ?)';
        params.push(kw, kw, kw);
      }
      const total = get(`SELECT COUNT(*) as c FROM recharge_orders ro LEFT JOIN users u ON ro.user_id=u.id ${where}`, params).c;
      const list = all(`SELECT ro.*, u.nickname, u.phone FROM recharge_orders ro LEFT JOIN users u ON ro.user_id=u.id ${where} ORDER BY ro.id DESC LIMIT ? OFFSET ?`, [...params, ps, (p - 1) * ps]);
      return res.json(page(list, total, p, ps));
    }

    const total = get('SELECT COUNT(*) as c FROM recharge_orders WHERE user_id=?', [req.userId]).c;
    const list = all('SELECT * FROM recharge_orders WHERE user_id=? ORDER BY id DESC LIMIT ? OFFSET ?', [req.userId, ps, (p - 1) * ps]);
    return res.json(page(list, total, p, ps));
  } catch (e) { return res.json(fail('查询失败')); }
});

// 支付回调
router.post('/pay-callback', (req, res) => {
  try {
    // 🔒 资金安全：生产环境禁止无验签的回调（防止伪造充值/白嫖余额）
    if (!ALLOW_RECHARGE_CALLBACK) return res.status(403).json(fail('模拟充值回调已禁用', 403));
    const { order_no } = req.body;
    if (!order_no) return res.json(fail('参数错误'));
    const o = get('SELECT * FROM recharge_orders WHERE order_no=?', [order_no]);
    if (!o) return res.json(fail('订单不存在'));
    if (o.status === 'success') return res.json(success(null, '已处理'));
    transaction(() => {
      // 幂等：仅未成功订单可入账，防止重复回调重复加分
      const done = run("UPDATE recharge_orders SET status='success', paid_at=datetime('now','localtime') WHERE order_no=? AND status!='success'", [order_no]);
      if (done.changes === 0) return;
      run('UPDATE users SET balance=balance+? WHERE id=?',
        [(o.amount || 0) + (o.give_amount || 0), o.user_id]);
      // 充值赠送积分：发独立积分(不再污染 experience)
      if ((o.give_points || 0) > 0) {
        try {
          const pts = require('../lib/points');
          pts.addPoints(o.user_id, o.give_points || 0, 'recharge', o.order_no, '充值赠送积分');
        } catch(e) { console.error('[积分] 充值赠送积分失败:', e.message); }
      }
    });
    return res.json(success(null, '充值成功'));
  } catch (e) { return res.json(fail('回调处理失败')); }
});

// 新增套餐（管理员）
router.post('/plans', (req, res, next) => {
  require('../middleware/auth').authAdmin(req, res, () => {
    try {
      const { name, amount, give_amount, give_points, sort } = req.body;
      if (!name) return res.json(fail('请输入套餐名称'));
      if (!amount || amount <= 0) return res.json(fail('充值金额必须大于0'));
      const r = run('INSERT INTO recharge_plans(name,amount,give_amount,give_points,sort) VALUES(?,?,?,?,?)',
        [name, amount, give_amount || 0, give_points || 0, sort || 0]);
      logOp(req.userId, 'add', 'recharge', r.lastInsertRowid, '新增套餐: ' + name);
      return res.json(success({ id: r.lastInsertRowid }, '添加成功'));
    } catch (e) { return res.json(fail('添加失败')); }
  });
});

// 更新套餐
router.put('/plans/:id', (req, res, next) => {
  require('../middleware/auth').authAdmin(req, res, () => {
    try {
      const { name, amount, give_amount, give_points, sort } = req.body;
      const plan = get('SELECT * FROM recharge_plans WHERE id=?', [req.params.id]);
      if (!plan) return res.json(fail('套餐不存在'));
      run('UPDATE recharge_plans SET name=?,amount=?,give_amount=?,give_points=?,sort=? WHERE id=?',
        [name || plan.name, amount || plan.amount,
         give_amount !== undefined ? give_amount : plan.give_amount,
         give_points !== undefined ? give_points : plan.give_points,
         sort !== undefined ? sort : plan.sort, req.params.id]);
      logOp(req.userId, 'update', 'recharge', +req.params.id, '更新套餐: ' + (name || plan.name));
      return res.json(success(null, '更新成功'));
    } catch (e) { return res.json(fail('更新失败')); }
  });
});

// 删除套餐
router.delete('/plans/:id', (req, res, next) => {
  require('../middleware/auth').authAdmin(req, res, () => {
    try {
      const plan = get('SELECT name FROM recharge_plans WHERE id=?', [req.params.id]);
      run('DELETE FROM recharge_plans WHERE id=?', [req.params.id]);
      logOp(req.userId, 'delete', 'recharge', +req.params.id, '删除套餐: ' + (plan?.name || ''));
      return res.json(success(null, '删除成功'));
    } catch (e) { return res.json(fail('删除失败')); }
  });
});

// 上下架
router.put('/plans/:id/toggle', (req, res, next) => {
  require('../middleware/auth').authAdmin(req, res, () => {
    try {
      const plan = get('SELECT * FROM recharge_plans WHERE id=?', [req.params.id]);
      if (!plan) return res.json(fail('套餐不存在'));
      const ns = plan.status === 1 ? 0 : 1;
      run('UPDATE recharge_plans SET status=? WHERE id=?', [ns, req.params.id]);
      return res.json(success({ status: ns }, ns ? '已上架' : '已下架'));
    } catch (e) { return res.json(fail('操作失败')); }
  });
});

function logOp(aid, act, mod, tid, det) {
  try { run('INSERT INTO operation_logs(admin_id,action,module,target_id,detail) VALUES(?,?,?,?,?)', [aid, act, mod, tid || null, det || '']); } catch {}
}

module.exports = router;
