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

async function main() {
  const tempPassword = process.env.SEED_ADMIN_PASSWORD;
  if (!tempPassword || tempPassword.length < 12) {
    throw new Error("Set SEED_ADMIN_PASSWORD env var (>=12 chars) to seed admins");
  }
  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 { hash } = await import("@node-rs/argon2");

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

  const passwordHash = await hash(tempPassword, {
    memoryCost: 19_456,
    timeCost: 2,
    parallelism: 1,
  });

  const ADMINS = [
    { email: "atef@orthoglobe.org",     name: "Atef Hassan",     country: "United Kingdom", institution: "OrthoGlobe", professionalRole: "researcher" },
    { email: "atefabdo26399@gmail.com", name: "Atef Hassan",     country: "United Kingdom", institution: "OrthoGlobe", professionalRole: "researcher" },
    { email: "imam@orthoglobe.org",     name: "Mohamed A. Imam", country: "United Kingdom", institution: "OrthoGlobe", professionalRole: "consultant" },
  ];

  for (const a of ADMINS) {
    const existing = await db.select({ id: users.id }).from(users).where(eq(users.email, a.email)).limit(1);
    if (existing.length > 0) {
      console.log(`skipping ${a.email} (already exists)`);
      continue;
    }
    await db.insert(users).values({
      email: a.email,
      name: a.name,
      country: a.country,
      institution: a.institution,
      professionalRole: a.professionalRole,
      passwordHash,
      status: "active",
      role: "admin",
      approvedAt: new Date(),
    });
    console.log(`seeded admin ${a.email}`);
  }
  await sql.end();
  process.exit(0);
}

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