import { useQuery, UseQueryOptions } from '@tanstack/react-query';
import { useInject } from '@/lib/di/hooks/useInject';
import { POLICY_SERVICE_TOKEN } from '@/lib/di/tokens';
import { enhanceQueryResult } from '@/lib/di/hooks/useReactQueryWithApiError';
import { ApiError } from '@/lib/api/base/ApiError';
import { PolicySnapshotDto } from '@/lib/api/policy/PolicyApiClient';

export function useCapability(
  capabilityKey: string,
  options?: Omit<UseQueryOptions<PolicySnapshotDto, ApiError>, 'queryKey' | 'queryFn'>
) {
  const policyService = useInject(POLICY_SERVICE_TOKEN);

  const queryResult = useQuery({
    queryKey: ['policySnapshot', capabilityKey],
    queryFn: async () => {
      const result = await policyService.getSnapshot();
      if (result.isErr()) {
        const error = result.getError();
        throw new ApiError(error.message, 'SERVER_ERROR', { timestamp: new Date().toISOString() });
      }
      return result.unwrap();
    },
    staleTime: 60_000,
    gcTime: 5 * 60_000,
    ...options,
  });

  const enhancedResult = enhanceQueryResult(queryResult);

  // Add helper to get capability state
  const capabilityState = enhancedResult.data 
    ? policyService.getCapabilityState(enhancedResult.data, capabilityKey)
    : null;

  return {
    ...enhancedResult,
    capabilityState,
    isCapabilityEnabled: capabilityState === 'enabled',
    isCapabilityComingSoon: capabilityState === 'coming_soon',
  };
}
