#!/usr/bin/env node
import Database from 'better-sqlite3';
import { readFileSync, readdirSync } from 'fs';
import { join, dirname } from 'path';
import { fileURLToPath } from 'url';

const __dirname = dirname(fileURLToPath(import.meta.url));
const dbPath = join(__dirname, '..', 'bifrost.db');
const migrationsDir = join(__dirname, '..', 'migrations');

const db = new Database(dbPath);
db.pragma('journal_mode = WAL');
db.pragma('foreign_keys = ON');

db.exec(`CREATE TABLE IF NOT EXISTS _migrations (
  id         TEXT PRIMARY KEY,
  applied_at TEXT NOT NULL DEFAULT (datetime('now'))
)`);

const applied = new Set(
  db.prepare('SELECT id FROM _migrations').all().map(r => r.id)
);

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

let count = 0;
for (const file of files) {
  if (applied.has(file)) continue;
  const sql = readFileSync(join(migrationsDir, file), 'utf8');
  db.exec(sql);
  db.prepare('INSERT INTO _migrations (id) VALUES (?)').run(file);
  console.log(`  applied: ${file}`);
  count++;
}

if (count === 0) console.log('  nothing to apply — already up to date');
else console.log(`\n  ${count} migration(s) applied.`);
db.close();
