// Seed a baseline set of active notifications for the global banner.
// Running:
//   pnpm tsx src/lib/db/seed-notifications.ts
//
// Idempotent — keyed on title to avoid duplicating the same banner.

import { config } from "dotenv";
import path from "node:path";
config({ path: path.resolve(process.cwd(), ".env.local") });

type SeedNotification = {
  title: string;
  body: string;
  href: string | null;
  level: "info" | "warning" | "success";
  active: boolean;
};

const SEED: SeedNotification[] = [
  {
    title: "Membership applications are open",
    body: "Surgeons, trainees, and researchers — apply to OrthoGlobe in 2 minutes. We target a 72-hour review turnaround.",
    href: "/join",
    level: "info",
    active: true,
  },
];

async function main() {
  const databaseUrl = process.env.DATABASE_URL;
  if (!databaseUrl) throw new Error("DATABASE_URL not set");

  const postgres = (await import("postgres")).default;
  const { drizzle } = await import("drizzle-orm/postgres-js");
  const { eq } = await import("drizzle-orm");
  const schema = await import("./schema");
  const { notifications } = schema;

  const sql = postgres(databaseUrl, { max: 1 });
  const db = drizzle(sql, { schema });

  let inserted = 0;
  let updated = 0;
  for (const n of SEED) {
    const existing = await db
      .select({ id: notifications.id })
      .from(notifications)
      .where(eq(notifications.title, n.title))
      .limit(1);

    if (existing.length > 0) {
      await db
        .update(notifications)
        .set({
          body: n.body,
          href: n.href,
          level: n.level,
          active: n.active,
          updatedAt: new Date(),
        })
        .where(eq(notifications.id, existing[0].id));
      updated += 1;
      console.log(`~ updated "${n.title}"`);
    } else {
      await db.insert(notifications).values(n);
      inserted += 1;
      console.log(`+ inserted "${n.title}"`);
    }
  }

  console.log(
    `\nDone — ${inserted} inserted, ${updated} updated, ${SEED.length} total`,
  );
  await sql.end();
}

main().catch((err) => {
  console.error(err);
  process.exit(1);
});
