import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import {
  getCatalogueProducts,
  getImportedCatalogueRefs,
  importCatalogueProducts,
  getBrands,
  getProductSubcategories,
  getTenantCategories,
  removeFromStoreCatalogue,
  ImportCatalogueProductRequest
} from '../services/catalogueApi';

export function useCatalogueProducts(brand?: string, keyword?: string) {
  return useQuery({
    queryKey: ['catalogue', 'products', brand ?? 'all', keyword ?? ''],
    // Full catalogue is ~237 products across all brands today; fetch enough
    // in one page that "show everything" (no brand filter) actually does.
    queryFn: () => getCatalogueProducts({ brand, keyword, pagesize: 500 }),
  });
}

export function useImportedCatalogueRefs(tenantid: number, brand?: string) {
  return useQuery({
    queryKey: ['catalogue', 'imported', tenantid, brand ?? 'all'],
    queryFn: () => getImportedCatalogueRefs(tenantid, brand),
  });
}

export function useCatalogueBrands() {
  return useQuery({
    queryKey: ['catalogue', 'brands'],
    queryFn: () => getBrands(),
  });
}

export function useProductSubcategories(tenantid: number, categoryid?: number) {
  return useQuery({
    queryKey: ['catalogue', 'subcategories', tenantid, categoryid ?? 'all'],
    queryFn: () => getProductSubcategories(tenantid, categoryid),
  });
}

export function useTenantCategories(tenantid: number) {
  return useQuery({
    queryKey: ['catalogue', 'tenantCategories', tenantid],
    queryFn: () => getTenantCategories(tenantid),
  });
}

export function useImportCatalogueProduct(tenantid: number, locationid: number) {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: (items: ImportCatalogueProductRequest[]) => importCatalogueProducts(items),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['catalogue', 'imported', tenantid] });
      // Invalidate store catalogue (adjust queryKey if it differs from what fiestaQueries uses for live store stock)
      queryClient.invalidateQueries({ queryKey: ['fiesta', 'productLocations'] });
      queryClient.invalidateQueries({ queryKey: ['fiesta', 'productStocks'] });
      queryClient.invalidateQueries({ queryKey: ['fiesta', 'stockStatement'] });
    },
  });
}

export function useRemoveFromStoreCatalogue(tenantid: number, locationid: number) {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: (productid: number) => removeFromStoreCatalogue(tenantid, locationid, productid),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['catalogue', 'imported', tenantid] });
      queryClient.invalidateQueries({ queryKey: ['fiesta', 'productLocations'] });
      queryClient.invalidateQueries({ queryKey: ['fiesta', 'productStocks'] });
      queryClient.invalidateQueries({ queryKey: ['fiesta', 'stockStatement'] });
    },
  });
}
