import { eq } from "drizzle-orm";

import { auth } from "../lib/auth";
import { db } from "../lib/db";
import { user } from "../lib/db/schema";

// Refuse to run against a prod DB: this script hardcodes a known password.
if (process.env.NODE_ENV === "production") {
  console.error("Refusing to seed admin user with NODE_ENV=production — password is hardcoded.");
  process.exit(1);
}

const EMAIL = "bastien@elevaseo.com";
const NAME = "Bastien";
const PASSWORD = "Eleva2025!";

async function seed() {
  try {
    const created = await auth.api.signUpEmail({
      body: { name: NAME, email: EMAIL, password: PASSWORD },
    });
    console.log("User created:", created.user.email);
  } catch (e) {
    const msg = e instanceof Error ? e.message : String(e);
    if (msg.toLowerCase().includes("already") || msg.toLowerCase().includes("exists")) {
      console.log("User already exists, skipping signup");
    } else {
      console.error("Signup error:", msg);
      process.exit(1);
    }
  }

  const promoted = await db
    .update(user)
    .set({ role: "admin" })
    .where(eq(user.email, EMAIL))
    .returning({ id: user.id, email: user.email, role: user.role });

  if (promoted.length === 0) {
    console.error(`No user found with email ${EMAIL} after seed`);
    process.exit(1);
  }
  console.log("Promoted to admin:", promoted[0]);
  process.exit(0);
}

seed().catch((e) => {
  console.error(e);
  process.exit(1);
});
