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

/**
 * One-off: ensure Prof Mohamed A. Imam has an admin account at
 * `Dr.mohdn@gmail.com` with the specified password.
 *
 * If the account exists, role is set to admin, status to active, and the
 * password hash is refreshed. If not, the account is created with those
 * properties. Idempotent — safe to re-run.
 */

const TARGET_EMAIL = "dr.mohdn@gmail.com";
const TARGET_NAME = "Prof Mohamed A. Imam";
const TARGET_PASSWORD = "Zzamalek1!";

async function main() {
  if (!process.env.DATABASE_URL) 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 { hash } = await import("@node-rs/argon2");
  const schema = await import("../src/lib/db/schema");

  const sql = postgres(process.env.DATABASE_URL!, { max: 1 });
  const db = drizzle(sql, { schema });

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

  const [existing] = await db
    .select({
      id: schema.users.id,
      role: schema.users.role,
      status: schema.users.status,
    })
    .from(schema.users)
    .where(eq(schema.users.email, TARGET_EMAIL))
    .limit(1);

  if (existing) {
    await db
      .update(schema.users)
      .set({
        name: TARGET_NAME,
        role: "admin",
        status: "active",
        passwordHash,
        approvedAt: new Date(),
      })
      .where(eq(schema.users.id, existing.id));
    console.log(
      `updated existing row for ${TARGET_EMAIL} — role=admin, status=active, password refreshed`,
    );
  } else {
    await db.insert(schema.users).values({
      email: TARGET_EMAIL,
      name: TARGET_NAME,
      country: "United Kingdom",
      institution: "OrthoGlobe",
      professionalRole: "consultant",
      passwordHash,
      status: "active",
      role: "admin",
      approvedAt: new Date(),
    });
    console.log(`inserted new admin row for ${TARGET_EMAIL}`);
  }

  const rows = await db
    .select({
      email: schema.users.email,
      name: schema.users.name,
      role: schema.users.role,
      status: schema.users.status,
    })
    .from(schema.users)
    .where(eq(schema.users.role, "admin"));
  console.log("\nAdmin roster:");
  console.table(rows);

  await sql.end();
}

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