/**
 * One-time setup: creates the single admin_users row.
 * Run with: npx tsx scripts/create-admin.ts you@example.com "a strong password"
 *
 * Prints the TOTP secret (base32) once — add it to an authenticator app
 * (Google Authenticator, 1Password, etc.) immediately, it is not shown again.
 */
import { randomBytes, scryptSync } from "crypto";
import { createClient } from "@supabase/supabase-js";

const supabase = createClient(
  process.env.NEXT_PUBLIC_SUPABASE_URL!,
  process.env.SUPABASE_SERVICE_ROLE_KEY!
);

function hashPassword(password: string): string {
  const salt = randomBytes(16);
  const hash = scryptSync(password, salt, 64);
  return `${salt.toString("hex")}:${hash.toString("hex")}`;
}

function randomBase32Secret(bytes = 20): string {
  const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
  const raw = randomBytes(bytes);
  let bits = "";
  for (const b of raw) bits += b.toString(2).padStart(8, "0");
  let out = "";
  for (let i = 0; i + 5 <= bits.length; i += 5) {
    out += alphabet[parseInt(bits.slice(i, i + 5), 2)];
  }
  return out;
}

async function main() {
  const [email, password] = process.argv.slice(2);
  if (!email || !password) {
    console.error('Usage: npx tsx scripts/create-admin.ts you@example.com "password"');
    process.exit(1);
  }

  const totpSecret = randomBase32Secret();
  const { error } = await supabase.from("admin_users").upsert(
    { email, password_hash: hashPassword(password), totp_secret: totpSecret },
    { onConflict: "email" }
  );
  if (error) throw error;

  console.log("Admin user created.");
  console.log("Email:      ", email);
  console.log("TOTP secret:", totpSecret);
  console.log("\nAdd that secret to an authenticator app now — it won't be shown again.");
}

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