import { useQuery } from '@tanstack/react-query';
import { deepCamelKeys } from 'string-ts';

import { useApiClient } from '@/lib/apiClient';

interface CommercialRightsEligibilityResponse {
  eligible: boolean;
}

/**
 * Hook to check if a clip is eligible for commercial rights purchase.
 * Uses the backend API to determine if the clip is a remix of someone else's work.
 */
export const useCommercialRightsEligibility = (clipId: string) => {
  const apiClient = useApiClient();

  return useQuery({
    queryKey: ['commercialRightsEligibility', clipId],
    queryFn: async (): Promise<CommercialRightsEligibilityResponse> => {
      const response = await apiClient.GET(
        '/api/clips/{clip_id}/commercial_rights_eligible',
        {
          params: { path: { clip_id: clipId } },
        }
      );

      if (!response.data) {
        throw new Error('Failed to check commercial rights eligibility');
      }

      return deepCamelKeys(
        response.data
      ) as CommercialRightsEligibilityResponse;
    },
    staleTime: 5 * 60 * 1000, // Cache for 5 minutes since eligibility shouldn't change often
    retry: (failureCount, error: any) => {
      // Don't retry on 404 (clip not found) or 403 (unauthorized)
      if (error?.status === 404 || error?.status === 403) {
        return false;
      }
      return failureCount < 3;
    },
    // Only run the query if we have a valid clipId
    enabled: Boolean(clipId),
  });
};
