const fs = require('fs');
const path = require('path');
const db = require('../config/database');

const migrationsDir = path.join(__dirname, 'migrations');

function getExecutedMigrations() {
  try {
    return db.prepare('SELECT name FROM migrations').all().map(m => m.name);
  } catch (err) {
    // migrations 表可能还不存在（第一次运行）
    return [];
  }
}

function runMigration(filename) {
  const filepath = path.join(migrationsDir, filename);
  const sql = fs.readFileSync(filepath, 'utf-8');

  console.log(`Running migration: ${filename}`);
  db.exec(sql);
  db.prepare('INSERT INTO migrations (name) VALUES (?)').run(filename);
  console.log(`Completed: ${filename}`);
}

function migrate() {
  const executed = getExecutedMigrations();
  const files = fs.readdirSync(migrationsDir)
    .filter(f => f.endsWith('.sql'))
    .filter(f => !executed.includes(f))
    .sort();

  for (const file of files) {
    runMigration(file);
  }

  if (files.length === 0) {
    console.log('No pending migrations.');
  } else {
    console.log(`Completed ${files.length} migration(s).`);
  }
}

migrate();
