import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import api from '@/services/api';
import type { Product, Category } from '@/types';

// Products - matches backend ProductsController
export function useProducts(categoryId?: string) {
  return useQuery({
    queryKey: ['products', categoryId],
    queryFn: async () => {
      const params = new URLSearchParams();
      if (categoryId) params.append('categoryId', categoryId);
      params.append('isActive', 'true');

      const { data } = await api.get<Product[]>(`/products?${params}`);
      return data;
    },
  });
}

export function useFavoriteProducts() {
  return useQuery({
    queryKey: ['products', 'favorites'],
    queryFn: async () => {
      // Backend: GET /products?isFavorite=true
      const { data } = await api.get<Product[]>('/products?isFavorite=true&isActive=true');
      return data;
    },
  });
}

export function useSearchProduct() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: async (barcode: string) => {
      // Backend: GET /products/barcode/:barcode
      const { data } = await api.get<Product>(`/products/barcode/${barcode}`);
      return data;
    },
    onSuccess: (product) => {
      queryClient.setQueryData(['product', product.id], product);
    },
  });
}

export function useToggleFavorite() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: async (productId: string) => {
      // Backend: PATCH /products/:id/toggle-favorite
      const { data } = await api.patch<Product>(`/products/${productId}/toggle-favorite`);
      return data;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['products'] });
    },
  });
}

// Categories - matches backend CategoriesController
export function useCategories() {
  return useQuery({
    queryKey: ['categories'],
    queryFn: async () => {
      const { data } = await api.get<Category[]>('/categories');
      return data;
    },
  });
}
