import Database from 'better-sqlite3';
import { existsSync, copyFileSync } from 'node:fs';
import { runMigrations, latestVersion } from './migrations/index.js';

export function openDb(dbFile: string): Database.Database {
  // F6-L1 follow-up #4: snapshot pre-migration if upgrading
  if (existsSync(dbFile)) {
    const probe = new Database(dbFile, { readonly: true });
    const cur = probe.pragma('user_version', { simple: true }) as number;
    probe.close();
    if (cur < latestVersion()) {
      const bak = `${dbFile}.pre-v${latestVersion()}.bak`;
      if (!existsSync(bak)) {
        copyFileSync(dbFile, bak);
      }
    }
  }
  const db = new Database(dbFile);
  db.pragma('journal_mode = WAL');
  db.pragma('foreign_keys = ON');
  runMigrations(db);
  return db;
}
