import { useEffect } from "react";
import { useNavigate } from "@remix-run/react";
import { useServiceGetProfile } from "~/requestHandler/use-profile-hooks";

/**
 * Gate a route to platform superusers. Non-admins (or unauthenticated) are
 * bounced to the home page. Server-side, `/admin` is also in `protectedRoutes`
 * so logged-out users never reach here — this adds the is-superuser check.
 */
export function useRequireAdmin() {
  const navigate = useNavigate();
  const { data, isLoading, isError } = useServiceGetProfile();
  const isAdmin = !!data?.isSuperuser;

  useEffect(() => {
    if (isLoading) return;
    if (isError || !isAdmin) {
      navigate("/", { replace: true });
    }
  }, [isLoading, isError, isAdmin, navigate]);

  return { isLoading, isAdmin };
}
