/**
 * useVariations Hook
 * 
 * TanStack Query hook for fetching and managing variations data
 */

import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { getVariations, updateVariation } from '../services/variations';
import type { VariationsQueryParams, Variation } from '../types/variation';

/**
 * Fetch variations with filters
 */
export function useVariations(params: VariationsQueryParams = {}) {
  return useQuery({
    queryKey: ['variations', params],
    queryFn: () => getVariations(params),
    staleTime: 30000, // 30 seconds
    refetchOnWindowFocus: false,
    placeholderData: (previousData) => previousData, // ⚠️ CRITICAL: Keep old data while fetching new
  });
}

/**
 * Update single variation (mutation)
 */
export function useUpdateVariation() {
  const queryClient = useQueryClient();
  
  return useMutation({
    mutationFn: ({ id, data }: { id: number; data: Partial<Variation> }) => {
      console.log('[useUpdateVariation] mutationFn CALLED with:', { id, data });
      return updateVariation(id, data);
    },
    onSuccess: (result, variables) => {
      console.log('[useUpdateVariation] onSuccess CALLED!');
      console.log('[useUpdateVariation] Result:', result);
      console.log('[useUpdateVariation] Variables:', variables);
      
      // 🎯 Optimistic update: Manually update cache without refetching
      queryClient.setQueriesData(
        { queryKey: ['variations'] },
        (oldData: any) => {
          if (!oldData?.data) {
            console.warn('[useUpdateVariation] NO oldData.data found!');
            return oldData;
          }
          
          console.log('[useUpdateVariation] Updating cache for variation:', variables.id);
          console.log('[useUpdateVariation] Cache structure:', Object.keys(oldData.data));
          
          // ✅ FLAT MODE: data.variations array
          if (oldData.data.variations) {
            return {
              ...oldData,
              data: {
                ...oldData.data,
                variations: oldData.data.variations.map((v: Variation) => {
                  if (v.id !== variables.id) return v;
                  
                  // Update variation with new data from API response (not variables.data!)
                  const updatedVariation = { ...v, ...result };
                  console.log('[useUpdateVariation] FLAT MODE updated variation:', updatedVariation);
                  return updatedVariation;
                }),
              },
            };
          }
          
          // ✅ GROUPED MODE: data.parents array with nested variations
          if (oldData.data.parents) {
            return {
              ...oldData,
              data: {
                ...oldData.data,
                parents: oldData.data.parents.map((parent: any) => {
                  // Find if this parent contains our variation
                  const hasVariation = parent.variations?.some((v: Variation) => v.id === variables.id);
                  
                  if (!hasVariation) return parent;
                  
                  // Update the variation inside this parent
                  return {
                    ...parent,
                    variations: parent.variations.map((v: Variation) => {
                      if (v.id !== variables.id) return v;
                      
                      // Update variation with new data from API response (not variables.data!)
                      const updatedVariation = { ...v, ...result };
                      console.log('[useUpdateVariation] GROUPED MODE updated variation:', updatedVariation);
                      return updatedVariation;
                    }),
                  };
                }),
              },
            };
          }
          
          console.warn('[useUpdateVariation] Unknown cache structure!', oldData.data);
          return oldData;
        }
      );
      
      // ⚠️ NO invalidateQueries - prevent loading indicator!
      // queryClient.invalidateQueries({ queryKey: ['variations'] });
    },
    onError: (error, variables) => {
      console.error('[useUpdateVariation] onError CALLED!', error, variables);
    },
  });
}
