import { useState, useEffect } from "react";
import { supabase } from "@/integrations/supabase/client";

export const useAdminExists = () => {
  const [hasAdmin, setHasAdmin] = useState<boolean | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const checkForAdmin = async () => {
      try {
        // Use the security-definer RPC which bypasses RLS
        const { data, error } = await supabase.rpc('no_admin_exists');

        if (error) {
          console.error("Error checking for admin:", error);
          setHasAdmin(true); // Assume admin exists on error to hide setup link
        } else {
          // no_admin_exists returns true when NO admin exists
          // So hasAdmin is the inverse
          setHasAdmin(!data);
        }
      } catch (error) {
        console.error("Error:", error);
        setHasAdmin(true);
      } finally {
        setLoading(false);
      }
    };

    checkForAdmin();
  }, []);

  return { hasAdmin, loading };
};
