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

interface SetupStatus {
  needsSetup: boolean | null;
  loading: boolean;
  error: string | null;
}

export const useSetupCheck = () => {
  const [status, setStatus] = useState<SetupStatus>({
    needsSetup: null,
    loading: true,
    error: null,
  });

  useEffect(() => {
    const checkSetupStatus = async () => {
      try {
        // Check if any admin exists using the database function
        const { data, error } = await supabase.rpc('no_admin_exists');
        
        if (error) {
          console.error("Error checking setup status:", error);
          // If there's an error, assume setup is complete to avoid blocking
          setStatus({ needsSetup: false, loading: false, error: error.message });
          return;
        }
        
        // data === true means no admin exists, so setup is needed
        setStatus({ needsSetup: data === true, loading: false, error: null });
      } catch (err) {
        console.error("Setup check failed:", err);
        setStatus({ needsSetup: false, loading: false, error: "Failed to check setup status" });
      }
    };

    checkSetupStatus();
  }, []);

  return status;
};
