// Forward-only migration runner. Applies any .sql in migrations/ not yet recorded.
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { db, execute, query } from './client.js';

const here = path.dirname(fileURLToPath(import.meta.url));
const migrationsDir = path.join(here, 'migrations');

async function run() {
  await execute(
    `CREATE TABLE IF NOT EXISTS _migrations (name TEXT PRIMARY KEY, applied_at INTEGER NOT NULL)`
  );
  const appliedRows = await query(`SELECT name FROM _migrations`);
  const applied = new Set(appliedRows.map((r) => r.name));

  const files = fs
    .readdirSync(migrationsDir)
    .filter((f) => f.endsWith('.sql'))
    .sort();

  for (const file of files) {
    if (applied.has(file)) {
      console.log('skip   ', file);
      continue;
    }
    const sql = fs.readFileSync(path.join(migrationsDir, file), 'utf8');
    console.log('apply  ', file);
    await db.executeMultiple(sql);
    await execute(`INSERT INTO _migrations (name, applied_at) VALUES (?, ?)`, [
      file,
      Math.floor(Date.now() / 1000),
    ]);
  }
  console.log('migrations complete');
  process.exit(0);
}

run().catch((err) => {
  console.error('migration failed:', err);
  process.exit(1);
});
