import { redirect } from "next/navigation";
import { createClient } from "@/lib/supabase/server";
import { AdminMembersTable } from "./admin-members-table";

export default async function AdminPage() {
  const supabase = await createClient();
  const {
    data: { user },
  } = await supabase.auth.getUser();

  if (!user) {
    redirect("/login");
  }

  const { data: callerProfile } = await supabase
    .from("profiles")
    .select("role")
    .eq("id", user.id)
    .single();

  // Vérification côté serveur : un "public" ne doit jamais pouvoir
  // atteindre cette page, même en tapant l'URL directement.
  if (callerProfile?.role !== "judge") {
    redirect("/leaderboard");
  }

  const { data: members } = await supabase
    .from("profiles")
    .select("id, pseudo, role, pseudo_locked, avatar_url")
    .order("pseudo", { ascending: true });

  return (
    <div className="mx-auto w-full max-w-3xl px-4 py-8">
      <div className="mb-6">
        <h1 className="font-heading text-2xl tracking-[0.1em] text-gold-bright uppercase">
          Le Conseil des Archontes
        </h1>
        <p className="font-serif text-sm text-marble/60 italic">Administration des Citoyens</p>
      </div>
      <AdminMembersTable members={members ?? []} currentUserId={user.id} />
    </div>
  );
}
