import type Database from 'better-sqlite3';
import * as m001 from './m001_initial.js';
import * as m002 from './m002_due_date.js';
import * as m003 from './m003_soft_delete.js';
import * as m004 from './m004_status.js';
import * as m005 from './m005_ai_disabled.js';
import * as m006 from './m006_revisions.js';
import * as m007 from './m007_fts.js';

const migrations = [m001, m002, m003, m004, m005, m006, m007];

export function latestVersion(): number {
  return migrations[migrations.length - 1]!.version;
}

export function runMigrations(db: Database.Database): void {
  const row = db.prepare('PRAGMA user_version').get() as { user_version: number };
  const current = row.user_version ?? 0;
  for (const m of migrations) {
    if (m.version > current) {
      const tx = db.transaction(() => {
        m.up(db);
        db.pragma(`user_version = ${m.version}`);
      });
      tx();
    }
  }
}
