/**
 * Ensures the baseline migration is marked as applied for databases
 * that were created with `drizzle-kit push` before we switched to
 * file-based migrations. Safe to run on fresh databases (no-op).
 */
import postgres from "postgres";
import { readFileSync } from "fs";
import { createHash } from "crypto";
import { resolve } from "path";

const sql = postgres(process.env.DATABASE_URL!);

try {
  // Check if any application tables exist (indicator of a push-created DB)
  const [{ exists: tablesExist }] = await sql`
    SELECT EXISTS (
      SELECT FROM information_schema.tables
      WHERE table_schema = 'public' AND table_name = 'paragraphs'
    ) as exists
  `;

  if (!tablesExist) {
    console.log("Fresh database — baseline seeding not needed.");
    await sql.end();
    process.exit(0);
  }

  // Ensure the drizzle schema + migrations table exist
  await sql`CREATE SCHEMA IF NOT EXISTS drizzle`;
  await sql`
    CREATE TABLE IF NOT EXISTS drizzle.__drizzle_migrations (
      id serial PRIMARY KEY,
      hash text NOT NULL,
      created_at bigint
    )
  `;

  // Check if any migrations are already recorded
  const [{ count }] = await sql`
    SELECT count(*)::int as count FROM drizzle.__drizzle_migrations
  `;

  if (Number(count) > 0) {
    console.log("Migration history already exists — baseline seeding not needed.");
    await sql.end();
    process.exit(0);
  }

  // Compute hash of the baseline migration and insert it
  const baselinePath = resolve(import.meta.dirname!, "../drizzle/0000_baseline.sql");
  const content = readFileSync(baselinePath, "utf-8");
  const hash = createHash("sha256").update(content).digest("hex");

  await sql`
    INSERT INTO drizzle.__drizzle_migrations (hash, created_at)
    VALUES (${hash}, ${Date.now()})
  `;

  console.log("Baseline migration marked as applied (push → migrate transition).");
} finally {
  await sql.end();
}
