/**
 * Classification React Query hooks
 */
import { useMutation, useQuery, useQueryClient, UseQueryOptions, UseMutationOptions } from '@tanstack/react-query';
import { classificationService } from '../services/classification';
import {
  ProductClassificationRequest,
  BatchClassificationRequest,
  ProductSuggestionResponse
} from '../types/classification';
import { ApiError } from '../client';

// Query Keys
export const classificationKeys = {
  all: ['classification'] as const,
  suggestions: {
    all: () => [...classificationKeys.all, 'suggestions'] as const,
    pending: (tenantId: string) => [...classificationKeys.suggestions.all(), 'pending', tenantId] as const,
    history: (tenantId: string, limit?: number, offset?: number) => 
      [...classificationKeys.suggestions.all(), 'history', tenantId, { limit, offset }] as const,
  },
  analysis: {
    all: () => [...classificationKeys.all, 'analysis'] as const,
    businessModel: (tenantId: string) => [...classificationKeys.analysis.all(), 'business-model', tenantId] as const,
  },
} as const;

// Mutations
export const useClassifyProduct = (
  options?: UseMutationOptions<
    ProductSuggestionResponse, 
    ApiError, 
    { tenantId: string; classificationData: ProductClassificationRequest }
  >
) => {
  const queryClient = useQueryClient();
  
  return useMutation<
    ProductSuggestionResponse, 
    ApiError, 
    { tenantId: string; classificationData: ProductClassificationRequest }
  >({
    mutationFn: ({ tenantId, classificationData }) => 
      classificationService.classifyProduct(tenantId, classificationData),
    onSuccess: (data, { tenantId }) => {
      // Invalidate pending suggestions to include the new one
      queryClient.invalidateQueries({ queryKey: classificationKeys.suggestions.pending(tenantId) });
    },
    ...options,
  });
};

export const useClassifyProductsBatch = (
  options?: UseMutationOptions<
    ProductSuggestionResponse[], 
    ApiError, 
    { tenantId: string; batchData: BatchClassificationRequest }
  >
) => {
  const queryClient = useQueryClient();
  
  return useMutation<
    ProductSuggestionResponse[], 
    ApiError, 
    { tenantId: string; batchData: BatchClassificationRequest }
  >({
    mutationFn: ({ tenantId, batchData }) => 
      classificationService.classifyProductsBatch(tenantId, batchData),
    onSuccess: (data, { tenantId }) => {
      // Invalidate pending suggestions to include the new ones
      queryClient.invalidateQueries({ queryKey: classificationKeys.suggestions.pending(tenantId) });
    },
    ...options,
  });
};