import { backupConfig, createBackup } from "../src/ops/backups";
import { databasePath } from "../src/db/config";
import { migrate } from "drizzle-orm/bun-sqlite/migrator";
import { db, sqlite } from "../src/db";

try {
  if (process.env.NODE_ENV === "production" && sqlite.query("SELECT name FROM sqlite_master WHERE name = 'habits'").get()) {
    // Fail before migrations if the safety snapshot cannot be created.
    createBackup(sqlite, backupConfig(databasePath));
  }
  migrate(db, { migrationsFolder: "./drizzle" });
  console.log("Database migrations applied.");
} finally {
  sqlite.close();
}
