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

// 用户优惠券列表（含状态筛选）
router.get('/user', authUser, (req, res) => {
  const { status } = req.query;
  let where = 'WHERE uc.user_id=?';
  const params = [req.userId];
  if (status === 'unused') { where += " AND uc.status='unused'"; }
  else if (status === 'used') { where += " AND uc.status='used'"; }
  else if (status === 'expired') { where += " AND uc.status='expired'"; }
  const list = all(`SELECT uc.*, c.name, c.type, c.value, c.min_amount AS condition_text, uc.expired_time AS expire_at
    FROM user_coupons uc JOIN coupons c ON uc.coupon_id=c.id ${where} ORDER BY uc.id DESC`, params);
  return res.json(success(list));
});

// 可用优惠券列表
router.get('/list', (req, res) => {
  const now = new Date().toISOString();
  const list = all("SELECT * FROM coupons WHERE status=1 AND (end_time IS NULL OR end_time>=?) ORDER BY id DESC", [now]);
  return res.json(success(list));
});

module.exports = router;
