import { useCallback, useEffect, useState } from 'react';

interface CapabilitiesApi {
  get: (path: string) => Promise<{ data: unknown }>; 
}

interface UseCapabilitiesOptions {
  api: CapabilitiesApi;
  notifyApiError?: (error: unknown, fallbackMessage: string) => void;
  token?: string | null;
}

const useCapabilities = ({ api, notifyApiError, token }: UseCapabilitiesOptions) => {
  const [capabilities, setCapabilities] = useState<string[]>([]);
  const [capabilitiesLoading, setCapabilitiesLoading] = useState(false);

  const refreshCapabilities = useCallback(async () => {
    if (!token) {
      setCapabilities([]);
      return;
    }
    setCapabilitiesLoading(true);
    try {
      const { data } = await api.get('/capabilities');
      if (Array.isArray(data)) {
        setCapabilities(data as string[]);
      } else {
        setCapabilities([]);
      }
    } catch (error) {
      notifyApiError?.(error, 'Failed to load capabilities.');
      setCapabilities([]);
    } finally {
      setCapabilitiesLoading(false);
    }
  }, [api, notifyApiError, token]);

  useEffect(() => {
    if (token) {
      refreshCapabilities();
    } else {
      setCapabilities([]);
    }
  }, [refreshCapabilities, token]);

  return {
    capabilities,
    capabilitiesLoading,
    refreshCapabilities,
  };
};

export default useCapabilities;
