/**
 * 营销自动化 · 管理端 API + 用户生日设置
 * ========================================
 * 管理端（/api/admin/marketing/automation）：规则 CRUD + 启停 + 日志 + 统计 + 手动执行
 * 用户端（/api/user/birthday）：个人中心设置生日（供生日礼）
 */
const express = require('express');
const router = express.Router();
const { get, all, run, transaction } = require('../utils/db');
const { success, fail, page } = require('../utils/response');
const { authAdmin, authUser } = require('../middleware/auth');
const { demoSafeGuard } = require('./admin-auth');
const engine = require('../lib/marketing-automation');

const TRIGGER_TYPES = ['cart_remind', 'birthday_gift', 'first_order', 'repurchase'];

// ============ 用户端：设置生日 ============
router.put('/birthday', authUser, (req, res) => {
  const { birthday } = req.body;
  if (!birthday) return res.json(fail('生日不能为空'));
  // 校验格式 MM-DD 或 YYYY-MM-DD
  const mmdd = String(birthday).slice(-5);
  if (!/^\d{2}-\d{2}$/.test(mmdd)) return res.json(fail('生日格式应为 MM-DD'));
  run('UPDATE users SET birthday=? WHERE id=?', [mmdd, req.userId]);
  return res.json(success(null, '生日设置成功'));
});

// ============ 管理端 ============

// 规则列表
router.get('/list', authAdmin, (req, res) => {
  const list = all("SELECT a.*, c.name coupon_name FROM marketing_automations a LEFT JOIN coupons c ON a.coupon_id=c.id ORDER BY a.id");
  return res.json(success(list));
});

// 新建/编辑
router.post('/', authAdmin, demoSafeGuard, (req, res) => {
  const { id, trigger_type, name, coupon_id, threshold_hours, repurchase_days, notify_template, title, valid_days, enabled } = req.body;
  if (!TRIGGER_TYPES.includes(trigger_type)) return res.json(fail('未知触发类型'));
  const nname = name || TRIGGER_TYPES.find(t => t === trigger_type) || trigger_type;
  try {
    if (id) {
      run(`UPDATE marketing_automations SET name=?,coupon_id=?,threshold_hours=?,repurchase_days=?,notify_template=?,title=?,valid_days=?,enabled=? WHERE id=?`,
        [nname, coupon_id || 0, threshold_hours || 3, repurchase_days || 15, notify_template || '', title || '', valid_days || 30, enabled === undefined ? 1 : enabled, id]);
      // 同类型仅允许一条？允许覆盖，但为避免多条同类型冲突，这里把同类型其他条停用
      run("UPDATE marketing_automations SET enabled=0 WHERE trigger_type=? AND id<>?", [trigger_type, id]);
      return res.json(success(null, '更新成功'));
    }
    const r = run(`INSERT INTO marketing_automations(trigger_type,name,coupon_id,threshold_hours,repurchase_days,notify_template,title,valid_days,enabled) VALUES(?,?,?,?,?,?,?,?,?)`,
      [trigger_type, nname, coupon_id || 0, threshold_hours || 3, repurchase_days || 15, notify_template || '', title || '', valid_days || 30, enabled === undefined ? 1 : enabled]);
    // 同类型仅一条启用
    run("UPDATE marketing_automations SET enabled=0 WHERE trigger_type=? AND id<>?", [trigger_type, r.lastInsertRowid]);
    return res.json(success(null, '创建成功'));
  } catch (e) {
    return res.json(fail('保存失败'));
  }
});

// 启停
router.post('/:id/toggle', authAdmin, demoSafeGuard, (req, res) => {
  const rule = get('SELECT * FROM marketing_automations WHERE id=?', [req.params.id]);
  if (!rule) return res.json(fail('规则不存在'));
  const nv = rule.enabled ? 0 : 1;
  run('UPDATE marketing_automations SET enabled=? WHERE id=?', [nv, rule.id]);
  if (nv) run('UPDATE marketing_automations SET enabled=0 WHERE trigger_type=? AND id<>?', [rule.trigger_type, rule.id]);
  return res.json(success({ enabled: nv }, nv ? '已启用' : '已停用'));
});

// 删除
router.delete('/:id', authAdmin, demoSafeGuard, (req, res) => {
  run('DELETE FROM marketing_automations WHERE id=?', [req.params.id]);
  return res.json(success(null, '已删除'));
});

// 手动立即执行（便于验证）
router.post('/:id/run', authAdmin, (req, res) => {
  const rule = get('SELECT * FROM marketing_automations WHERE id=?', [req.params.id]);
  if (!rule) return res.json(fail('规则不存在'));
  const r = engine.runRule(Object.assign({}, rule, { enabled: 1 }));
  return res.json(success(r, '执行完成'));
});

// 日志
router.get('/logs', authAdmin, (req, res) => {
  const { page: p = 1, pageSize = 20, trigger_type } = req.query;
  const pageNum = Math.max(1, +p);
  const size = Math.min(100, Math.max(1, +pageSize));
  let where = ' WHERE 1=1';
  const params = [];
  if (trigger_type) { where += ' AND l.trigger_type=?'; params.push(trigger_type); }
  const total = get(`SELECT COUNT(*) c FROM automation_logs l ${where}`, params).c;
  const list = all(`SELECT l.*, u.nickname, c.name coupon_name
    FROM automation_logs l
    LEFT JOIN users u ON l.user_id=u.id
    LEFT JOIN coupons c ON l.coupon_id=c.id
    ${where} ORDER BY l.id DESC LIMIT ? OFFSET ?`, [...params, size, (pageNum - 1) * size]);
  return res.json(page(list, total, pageNum, size));
});

// 统计
router.get('/stats', authAdmin, (req, res) => {
  const byType = all("SELECT trigger_type, COUNT(*) cnt, SUM(CASE WHEN status='success' THEN 1 ELSE 0 END) ok, SUM(CASE WHEN status='skipped' THEN 1 ELSE 0 END) skip, SUM(CASE WHEN status='error' THEN 1 ELSE 0 END) err FROM automation_logs GROUP BY trigger_type");
  const totalIssued = get("SELECT COUNT(*) c FROM automation_logs WHERE status='success'").c;
  return res.json(success({ byType, totalIssued, totalLogs: get('SELECT COUNT(*) c FROM automation_logs').c }));
});

module.exports = router;
