const express = require('express');

// [LiteMall_Copyright] fba28f00dae77aa2 LiteMall_Lobster_v1.0_2026


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 { isFeatureEnabled } = require('../lib/license');
// ========== 功能门控：付费会员套餐购买仅在完整版可用 ==========
// 保留套餐列表查询和基础等级展示
// 但拦截购买接口
// 会员套餐列表
router.get('/plans', (req, res) => {
  const plans = all('SELECT * FROM membership_plans WHERE status=1 ORDER BY sort ASC');
  return res.json(success(plans));
});
// 购买会员（付费版可用）
// 🔒 安全：只创建 pending_pay 待支付订单，不直接发放权益；
//    支付回调确认到账后由 lib/membership-activate.js 发放会员/经验/优惠券。
//    封堵“无支付校验免费开通会员”漏洞。
router.post('/buy', authUser, (req, res) => {
  if (!isFeatureEnabled('paid_membership')) {
    return res.json(fail('当前版本不支持购买付费会员套餐', 403));
  }
  try {
    const { plan_id, payment_method } = req.body;
    const pid = Math.floor(Number(plan_id));
    if (!Number.isFinite(pid) || pid < 1) return res.json(fail('套餐不存在'));
    const plan = get('SELECT * FROM membership_plans WHERE id=? AND status=1', [pid]);
    if (!plan) return res.json(fail('套餐不存在'));
    // 金额用整数分（money 工具），防浮点精度
    const { toNum } = require('../utils/money');
    const amount = toNum(plan.price);
    const orderNo = `VIP${Date.now()}${Math.floor(Math.random()*1000)}`;
    run(`INSERT INTO orders(order_no,user_id,total_amount,pay_amount,payment_method,status,remark)
      VALUES(?,?,?,?,?,?,?)`,
      [orderNo, req.userId, amount, amount, payment_method || 'wechat', 'pending_pay', `购买会员:${plan.name}:plan${pid}`]);
    return res.json(success({ order_no: orderNo, amount }, '下单成功，请完成支付'));
  } catch (e) {
    return res.json(fail('下单失败'));
  }
});
// 我的会员
router.get('/my', authUser, (req, res) => {
  const membership = get(`SELECT um.*, mp.name as plan_name, mp.type, mp.price 
    FROM user_memberships um JOIN membership_plans mp ON um.plan_id=mp.id 
    WHERE um.user_id=? AND um.status='active' ORDER BY um.id DESC LIMIT 1`, [req.userId]);
  const user = get('SELECT level_id, experience FROM users WHERE id=?', [req.userId]);
  const level = get('SELECT * FROM user_levels WHERE id=?', [user.level_id]);
  return res.json(success({ membership, level, experience: user.experience }));
});
// 购买记录
router.get('/history', authUser, (req, res) => {
  const list = all(`SELECT um.*, mp.name as plan_name, mp.price 
    FROM user_memberships um JOIN membership_plans mp ON um.plan_id=mp.id 
    WHERE um.user_id=? ORDER BY um.id DESC LIMIT 20`, [req.userId]);
  return res.json(success(list));
});
module.exports = router;