import dotenv from "dotenv";
import { createClient } from "@supabase/supabase-js";

dotenv.config({ path: ".env" });

function argument(name: string): string | null {
  const index = process.argv.indexOf(`--${name}`);
  return index >= 0 ? process.argv[index + 1]?.trim() || null : null;
}

function isServerKey(key: string): boolean {
  if (key.startsWith("sb_secret_")) return true;

  try {
    const payload = key.split(".")[1];
    if (!payload) return false;
    const claims = JSON.parse(Buffer.from(payload, "base64url").toString("utf8")) as { role?: string };
    return claims.role === "service_role";
  } catch {
    return false;
  }
}

async function main() {
  const projectId = process.env.SUPABASE_PROJECT_ID?.trim();
  const url = process.env.NEXT_PUBLIC_SUPABASE_URL?.trim() || (projectId ? `https://${projectId}.supabase.co` : null);
  const key = process.env.SUPABASE_SECRET_KEY?.trim();
  const email = argument("email")?.toLowerCase();
  const fullName = argument("name");
  const password = process.env.FIRST_ADMIN_PASSWORD;

  if (!url || !key) throw new Error("Set SUPABASE_PROJECT_ID (or NEXT_PUBLIC_SUPABASE_URL) and SUPABASE_SECRET_KEY.");
  if (!isServerKey(key)) {
    throw new Error("SUPABASE_SECRET_KEY must be a Supabase secret key or legacy service-role JWT, not a CLI or publishable key.");
  }
  if (!email || !fullName) throw new Error('Usage: npm run first-admin -- --email "admin@example.org" --name "Admin Name"');
  if (!password || password.length < 6) throw new Error("Set FIRST_ADMIN_PASSWORD to a unique password of at least 6 characters.");

  const supabase = createClient(url, key, {
    auth: { autoRefreshToken: false, persistSession: false }
  });
  const { count, error: countError } = await supabase
    .from("profiles")
    .select("id", { count: "exact", head: true })
    .eq("role", "admin");
  if (countError?.code === "42P01" || countError?.message.toLowerCase().includes("profiles")) {
    throw new Error("The database migration must be applied before creating the first admin.");
  }
  if (countError) throw new Error(`Unable to inspect existing administrators: ${countError.message}`);
  if ((count ?? 0) > 0) throw new Error("An administrator already exists. Create additional admins through a controlled database procedure.");

  const { data, error } = await supabase.auth.admin.createUser({
    email,
    password,
    email_confirm: true,
    user_metadata: { full_name: fullName, initial_role: "admin" }
  });
  if (error || !data.user) throw new Error("Unable to create the account. Use an email that is not already registered.");

  const { error: profileError } = await supabase.from("profiles").upsert({
    id: data.user.id,
    role: "admin",
    full_name: fullName,
    is_active: true
  });
  if (profileError) {
    await supabase.auth.admin.deleteUser(data.user.id);
    throw new Error("Unable to create the admin profile; the new auth user was rolled back.");
  }

  console.log(`First administrator created for ${email}.`);
}

main().catch((error: unknown) => {
  console.error(error instanceof Error ? error.message : "First-admin creation failed.");
  process.exitCode = 1;
});
