import {readdirSync, readFileSync} from "fs";
import path from "path";
import {Database} from "better-sqlite3"

export function runMigrations(db: Database) {
  db.exec(`
    CREATE TABLE IF NOT EXISTS migrations (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      name TEXT NOT NULL UNIQUE,
      apptiled_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    );
  `);

  const appliedMigrations = new Set(
    db.prepare("SELECT name FROM migrations").all()
      .map((m: any) => m.name)
  );

  const migrationFiles = readdirSync(path.resolve(__dirname, "migrations")).sort();

  for (const file of migrationFiles) {
    if (!appliedMigrations.has(file)) {
      console.log(`Applying migration: ${file}`);
      const sql = readFileSync(path.join(__dirname, "migrations", file), "utf8");
      db.exec(sql);
      db.prepare("INSERT INTO migrations (name) VALUES (?)").run(file);
    }
  }

  console.log("Migrations complete.");
}