/**
 * 营销自动化调度器
 * ================
 * 每 10 分钟扫描启用的自动化规则（cart_remind / birthday_gift / repurchase），
 * 命中即自动发券 + 站内通知。
 * first_order 为事件触发（order.js 支付成功后调用引擎.onOrderPaid），不在此扫描。
 */
const { all } = require('../utils/db');
const engine = require('../lib/marketing-automation');

const INTERVAL = 10 * 60 * 1000; // 每 10 分钟
let timer = null;
let running = false;
const hooks = { onScan: null, onError: null };

async function tick() {
  if (running) return;
  running = true;
  try {
    const rules = all("SELECT * FROM marketing_automations WHERE enabled=1 AND trigger_type != 'first_order' ORDER BY id");
    if (!rules.length) return;
    const results = [];
    for (const rule of rules) {
      results.push(engine.runRule(rule));
    }
    if (hooks.onScan) hooks.onScan(results);
  } catch (e) {
    if (hooks.onError) hooks.onError({ error: e, msg: '营销自动化调度异常' });
  } finally {
    running = false;
  }
}

function start() {
  if (timer) return;
  setTimeout(() => { tick().catch(() => {}); }, 5000); // 启动 5 秒后先跑一次
  timer = setInterval(() => { tick().catch(() => {}); }, INTERVAL);
  timer.unref && timer.unref();
  console.log('[营销自动化] 调度器已启动，每10分钟扫描一次');
}

function stop() { if (timer) { clearInterval(timer); timer = null; } }

module.exports = { start, stop, tick, hooks, INTERVAL };
