import { migrate } from "drizzle-orm/node-postgres/migrator";
import { db, pool } from "./index";

export async function runMigrations() {
  console.log("[db] Running migrations...");
  try {
    await migrate(db, { migrationsFolder: "./drizzle" });
    console.log("[db] Migrations completed successfully");
  } catch (error) {
    console.error("[db] Migration failed:", error);
    throw error;
  }
}

const isMainModule = process.argv[1]?.includes("migrate");
if (isMainModule) {
  runMigrations()
    .then(() => pool.end())
    .catch((error) => {
      console.error(error);
      process.exit(1);
    });
}
