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

// One-off upsert: promotes Atef A. Hassan to admin with a specific password.
// Safe to re-run — uses onConflictDoUpdate keyed on email.

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 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 email = "atefabdo26399@gmail.com";
  const plaintext = "AtefAbdo99";

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

  const now = new Date();
  await db
    .insert(users)
    .values({
      email,
      name: "Atef A. Hassan",
      country: "United Kingdom",
      institution: "OrthoGlobe",
      professionalRole: "researcher",
      passwordHash,
      status: "active",
      role: "admin",
      approvedAt: now,
    })
    .onConflictDoUpdate({
      target: users.email,
      set: {
        name: "Atef A. Hassan",
        passwordHash,
        status: "active",
        role: "admin",
        approvedAt: now,
      },
    });

  console.log(`Atef (${email}) is now an active admin.`);
  await sql.end();
  process.exit(0);
}

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