/**
 * Seed or update an admin user.
 * Usage: pnpm tsx scripts/create-admin.ts <email> <password> [name]
 * Requires DATABASE_URL in the environment.
 */
import argon2 from "argon2";
import * as db from "../server/db";

async function main() {
  const [, , emailArg, password, name] = process.argv;
  const email = emailArg?.trim().toLowerCase();

  if (!email || !password) {
    console.error("Usage: pnpm tsx scripts/create-admin.ts <email> <password> [name]");
    process.exit(1);
  }
  if (!process.env.DATABASE_URL) {
    console.error("DATABASE_URL is required.");
    process.exit(1);
  }

  const passwordHash = await argon2.hash(password);
  await db.upsertUser({
    email,
    passwordHash,
    name: name ?? null,
    role: "admin",
    loginMethod: "password",
    lastSignedIn: new Date(),
  });

  console.log(`✓ Admin user ready: ${email}`);
  process.exit(0);
}

main().catch((err) => {
  console.error("Failed to create admin:", err);
  process.exit(1);
});
