/**
 * Migration 002 — 添加检测相关字段到 products
 *
 * - check_mode: 检测模式 (keyword | api | manual)
 * - in_stock_keywords: 有货关键词 (逗号分隔)
 * - out_of_stock_keywords: 缺货关键词 (逗号分隔)
 */
const Database = require('better-sqlite3');
const path = require('path');
require('dotenv').config({ path: path.join(__dirname, '..', '.env') });

const dbPath = path.resolve(__dirname, '..', process.env.DB_PATH || 'db/monitor.sqlite');
const db = new Database(dbPath);
db.pragma('journal_mode = WAL');

function ensureColumn(table, column, sql) {
  const cols = db.prepare(`PRAGMA table_info(${table})`).all().map(c => c.name);
  if (!cols.includes(column)) {
    db.exec(`ALTER TABLE ${table} ADD COLUMN ${sql}`);
    console.log(`+ ${table}.${column}`);
  } else {
    console.log(`  ${table}.${column} (already exists)`);
  }
}

ensureColumn('products', 'check_mode', "check_mode TEXT DEFAULT 'keyword'");
ensureColumn('products', 'in_stock_keywords', 'in_stock_keywords TEXT');
ensureColumn('products', 'out_of_stock_keywords', 'out_of_stock_keywords TEXT');

// 为 GoMami 测试样例设置默认关键词
const gomami = db.prepare("SELECT id FROM products WHERE name LIKE '%Pulse%' AND check_mode IS NULL").all();
if (gomami.length > 0) {
  const stmt = db.prepare(`
    UPDATE products
    SET check_mode = 'keyword',
        in_stock_keywords = 'Add to Cart,立即购买,加入购物车',
        out_of_stock_keywords = 'Out of Stock,缺货,售罄,Sold Out,Currently Unavailable'
    WHERE id = ?
  `);
  for (const row of gomami) {
    stmt.run(row.id);
    console.log(`🏷  设置 product#${row.id} 的检测关键词`);
  }
}

console.log('✅ migration-002 done:', dbPath);
db.close();
