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

router.use(authUser);

// 购物车列表
router.get('/list', (req, res) => {
  const list = all(`SELECT c.id,c.product_id,c.sku_id,c.quantity,c.selected,
    p.name as product_name,p.image as product_image,p.price,p.subtitle,
    ps.price as sku_price,ps.image as sku_image,ps.specs,ps.stock as sku_stock
    FROM carts c 
    JOIN products p ON c.product_id=p.id
    LEFT JOIN product_skus ps ON c.sku_id=ps.id
    WHERE c.user_id=? ORDER BY c.id DESC`, [req.userId]);
  list.forEach(item => {
    if (item.specs) item.specs = JSON.parse(item.specs);
  });
  return res.json(success(list));
});

// 添加商品
router.post('/add', (req, res) => {
  const { product_id, sku_id, quantity } = req.body;
  if (!product_id) return res.json({ code: 1, message: '参数错误' });
  // 🔒 数量钳制：仅允许 1-999 正整数，防累加超大数量污染购物车/统计
  const qty = Math.max(1, Math.min(999, Math.floor(Number(quantity)) || 1));

  const exist = get('SELECT id,quantity FROM carts WHERE user_id=? AND product_id=? AND (sku_id=? OR (sku_id IS NULL AND ? IS NULL))',
    [req.userId, product_id, sku_id || null, sku_id || null]);

  if (exist) {
    run('UPDATE carts SET quantity=quantity+? WHERE id=?', [qty, exist.id]);
  } else {
    run('INSERT INTO carts(user_id,product_id,sku_id,quantity) VALUES(?,?,?,?)',
      [req.userId, product_id, sku_id || null, qty]);
  }
  return res.json(success(null, '已加入购物车'));
});

// 修改数量
router.put('/:id', (req, res) => {
  const { quantity } = req.body;
  // 🔒 数量钳制
  const qty = Math.max(1, Math.min(999, Math.floor(Number(quantity)) || 1));
  run('UPDATE carts SET quantity=? WHERE id=? AND user_id=?', [qty, req.params.id, req.userId]);
  return res.json(success(null, '更新成功'));
});

// 删除
router.delete('/:id', (req, res) => {
  run('DELETE FROM carts WHERE id=? AND user_id=?', [req.params.id, req.userId]);
  return res.json(success(null, '删除成功'));
});

// 清空
router.delete('/', (req, res) => {
  run('DELETE FROM carts WHERE user_id=?', [req.userId]);
  return res.json(success(null, '已清空'));
});

// 选中/取消选中
router.post('/toggle-select', (req, res) => {
  const { id, selected } = req.body;
  run('UPDATE carts SET selected=? WHERE id=? AND user_id=?', [selected ? 1 : 0, id, req.userId]);
  return res.json(success(null, '更新成功'));
});

// 全选/取消全选
router.post('/select-all', (req, res) => {
  const { selected } = req.body;
  run('UPDATE carts SET selected=? WHERE user_id=?', [selected ? 1 : 0, req.userId]);
  return res.json(success(null, '更新成功'));
});

module.exports = router;
