/**
 * Migration 005 — Aff Code 字段
 *
 * - aff_code: 用户的 aff 标识值（如 "5"），用于自动生成 aff 链接
 * - aff_param: aff 参数名（默认 "aff"），支持不同商家用不同参数名
 */
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', 'aff_code', 'aff_code TEXT');
ensureColumn('products', 'aff_param', "aff_param TEXT DEFAULT 'aff'");

// 回填：从已有 buy_url 中解析 aff_code
const { parseAffCode } = require('../src/utils/affHelper');

const products = db.prepare('SELECT id, buy_url, url, aff_code FROM products').all();
const updateStmt = db.prepare('UPDATE products SET aff_code = ? WHERE id = ?');

db.transaction(() => {
  for (const p of products) {
    if (p.aff_code) continue; // 已有值，跳过
    const parsed = parseAffCode(p.buy_url) || parseAffCode(p.url);
    if (parsed) {
      updateStmt.run(parsed.value, p.id);
      console.log(`  product #${p.id}: aff_code=${parsed.value} (from ${parsed.param}=${parsed.value})`);
    }
  }
})();

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