/**
 * 任务执行器 — 执行单个监控任务的核心逻辑
 *
 * 流程:
 *   1. 查询任务 + 关联产品信息
 *   2. 调用 checker 检测库存
 *   3. 写入 check_logs
 *   4. 更新 products.in_stock / last_checked
 *   5. 更新 monitor_tasks.last_run
 *   6. 如果状态变化且配置了频道 → 推送 Telegram
 */
const db = require('../db');
const { checkProduct } = require('./checker');
const { sendMessage } = require('./telegram');
const { buildPushMessage } = require('./pushTemplate');

/**
 * 执行一个监控任务
 * @param {number} taskId — monitor_tasks.id
 * @returns {Promise<{ success: boolean, status: string, message: string, notified: boolean }>}
 */
async function runTask(taskId) {
  // 1. 查询任务 + 产品
  const task = db.prepare(`
    SELECT t.*, c.chat_id AS channel_chat_id, c.name AS channel_name
    FROM monitor_tasks t
    LEFT JOIN tg_channels c ON t.tg_channel_id = c.id
    WHERE t.id = ?
  `).get(taskId);

  if (!task) {
    return { success: false, status: 'error', message: `任务 #${taskId} 不存在`, notified: false };
  }

  const product = db.prepare(`
    SELECT p.*, m.name AS merchant_name,
           p.generated_aff_url AS product_aff_url,
           (SELECT url FROM aff_links a WHERE a.product_id = p.id AND a.platform = 'telegram' ORDER BY a.id DESC LIMIT 1) AS tg_aff_url,
           (SELECT url FROM aff_links a WHERE a.product_id = p.id ORDER BY a.id DESC LIMIT 1) AS any_aff_url
    FROM products p
    LEFT JOIN merchants m ON p.merchant_id = m.id
    WHERE p.id = ?
  `).get(task.product_id);

  if (!product) {
    return { success: false, status: 'error', message: `产品 #${task.product_id} 不存在`, notified: false };
  }

  // 记录之前的状态
  const prevStock = product.in_stock;

  // 2. 执行检测
  const { status, message } = await checkProduct(product);
  const now = new Date().toISOString();

  // 3. 状态码映射: in_stock=1, out_of_stock=2, error=0(保持不变)
  const stockCode = status === 'in_stock' ? 1 : status === 'out_of_stock' ? 2 : product.in_stock;

  // 4. 写入 check_logs
  db.prepare(`
    INSERT INTO check_logs (task_id, product_id, status, message) VALUES (?, ?, ?, ?)
  `).run(taskId, product.id, status, message);

  // 5. 更新 products
  db.prepare(`
    UPDATE products SET in_stock = ?, last_checked = ?, updated_at = ? WHERE id = ?
  `).run(stockCode, now, now, product.id);

  // 6. 更新 monitor_tasks.last_run
  db.prepare(`
    UPDATE monitor_tasks SET last_run = ? WHERE id = ?
  `).run(now, taskId);

  // 7. 判断是否需要推送
  let notified = false;
  const stateChanged = prevStock !== stockCode;
  const becameInStock = stockCode === 1 && prevStock !== 1;

  if (becameInStock && task.channel_chat_id) {
    // 补货了！推送通知
    // 链接优先级：1. 产品生成的 aff 链接 2. aff_links 表 3. buy_url
    const affUrl = product.product_aff_url || product.tg_aff_url || product.any_aff_url || null;
    const pushText = buildPushMessage({ ...product, aff_url: affUrl, merchant_name: product.merchant_name });
    const tgResult = await sendMessage(task.channel_chat_id, pushText);
    notified = tgResult.ok === true;

    // 更新 check_logs.notified
    if (notified) {
      db.prepare(`
        UPDATE check_logs SET notified = 1 WHERE task_id = ? AND product_id = ? ORDER BY id DESC LIMIT 1
      `).run(taskId, product.id);
    }
  }

  const statusLabel = { in_stock: '有货 ✅', out_of_stock: '缺货 ❌', error: '错误 ⚠️' };
  const resultMsg = [
    `${statusLabel[status] || status}: ${message}`,
    stateChanged ? `（状态变化: ${prevStock} → ${stockCode}）` : '（状态无变化）',
    notified ? '📨 已推送' : '',
  ].filter(Boolean).join(' ');

  return { success: true, status, message: resultMsg, notified };
}

module.exports = { runTask };
