/**
 * Standalone database migration runner.
 *
 * This runs as its OWN process on container startup, before the Next.js
 * server boots (see Dockerfile CMD). It is intentionally separate from
 * src/db/index.ts: that module configures a long-lived connection POOL for
 * the running app; migrations want a single short-lived connection that is
 * closed the moment they finish.
 *
 * Build note: this file is bundled by scripts/build-migrator.mjs into a
 * self-contained dist/migrate.mjs (drizzle-orm + postgres inlined) so the
 * production image needs no extra runtime dependencies.
 */
import { drizzle } from "drizzle-orm/postgres-js";
import { migrate } from "drizzle-orm/postgres-js/migrator";
import postgres from "postgres";

async function main() {
  // Prefer DATABASE_URL_SUPERUSER for DDL (CREATE TABLE, RLS, etc).
  // Falls back to DATABASE_URL so local dev with a single URL still works.
  const url = process.env.DATABASE_URL_SUPERUSER ?? process.env.DATABASE_URL;
  if (!url) {
    console.error("[migrate] Neither DATABASE_URL_SUPERUSER nor DATABASE_URL is set — aborting.");
    process.exit(1);
  }

  // max: 1 — a migration run is sequential; a single connection is correct
  // and avoids holding pool slots. The connection is closed in finally{}.
  const client = postgres(url, { max: 1 });

  try {
    // The baseline schema uses pgvector (memories.vision_embedding vector(1536)
    // + ivfflat index), so the `vector` extension MUST exist before migrations
    // run. We do it here — not in a migration file — because CREATE EXTENSION
    // needs a superuser (this runner uses DATABASE_URL_SUPERUSER). Idempotent.
    //
    // This only succeeds if the Postgres image actually ships the pgvector
    // binaries (e.g. the pgvector/pgvector image). A plain `postgres` image
    // will fail here with "could not access file vector" — that's an infra
    // problem (wrong DB image), and failing loud is correct.
    console.log("[migrate] ensuring pgvector 'vector' extension...");
    try {
      await client`CREATE EXTENSION IF NOT EXISTS vector`;
      console.log("[migrate] pgvector extension ready.");
    } catch (extErr) {
      console.error(
        "[migrate] FAILED to create the pgvector 'vector' extension.\n" +
        "  → The Postgres image must include pgvector (use the pgvector/pgvector image,\n" +
        "    e.g. pgvector/pgvector:pg18 to match prod), and the migration connection\n" +
        "    (DATABASE_URL_SUPERUSER) must be a superuser.",
        extErr
      );
      throw extErr;
    }

    console.log("[migrate] applying pending migrations...");
    await migrate(drizzle(client), { migrationsFolder: "./drizzle" });
    console.log("[migrate] done — schema is up to date.");
  } catch (err) {
    // Fail LOUD. If migration fails we must NOT let the app boot against a
    // half-migrated schema — a crashed container is a visible, safe failure.
    console.error("[migrate] FAILED:", err);
    process.exit(1);
  } finally {
    await client.end();
  }
}

main();
