// src/lib/db-migrations.ts
import fs from "fs/promises";
var MIGRATIONS = [
  { version: "001", file: "001-initial-schema.sql" },
  { version: "002", file: "002-add-contacts.sql" },
  { version: "003", file: "003-backfill-contacts.sql" }
];
var CREATE_MIGRATIONS_TABLE_SQL = `
  CREATE TABLE IF NOT EXISTS schema_migrations (
    version TEXT NOT NULL PRIMARY KEY,
    applied_at TEXT NOT NULL
  )
`;
function nowIso() {
  return (/* @__PURE__ */ new Date()).toISOString();
}
async function readMigrationSql(file) {
  return await fs.readFile(new URL(`./migrations/${file}`, import.meta.url), "utf8");
}
function listAppliedVersions(db) {
  const rows = db.prepare("SELECT version FROM schema_migrations").all();
  return new Set(
    rows.map((row) => typeof row.version === "string" ? row.version : "").filter(Boolean)
  );
}
async function runMigrations(db) {
  db.exec(CREATE_MIGRATIONS_TABLE_SQL);
  const applied = listAppliedVersions(db);
  for (const migration of MIGRATIONS) {
    if (applied.has(migration.version)) {
      continue;
    }
    const sql = await readMigrationSql(migration.file);
    db.exec("BEGIN");
    try {
      db.exec(sql);
      db.prepare(
        "INSERT INTO schema_migrations (version, applied_at) VALUES (?, ?)"
      ).run(migration.version, nowIso());
      db.exec("COMMIT");
    } catch (error) {
      try {
        db.exec("ROLLBACK");
      } catch {
      }
      throw error;
    }
  }
}
export {
  runMigrations
};
