import { useInfiniteQuery } from "@tanstack/react-query";
import * as api from "../service/Service";
import { ProductsResponse } from "@/types/products.types";

interface UseInfiniteProductsDataParams {
  page?: number;
  limit?: number;
  category?: string;
  brand?: string;
  minPrice?: number;
  maxPrice?: number;
  attributes?: string[];
  sizes?: number[];
  meterages?: number[];
  sort?: string;
  wholeSale?: string;
  stock?: string;
  rating?: number;
}

export const useInfiniteProductsData = (
  params?: UseInfiniteProductsDataParams
) => {
  return useInfiniteQuery<ProductsResponse>({
    queryKey: ["infinite-products", params],
    queryFn: ({ pageParam = 1 }) =>
      api.getProducts({ ...params, page: pageParam as number }),
    getNextPageParam: (lastPage) => {
      const pager = lastPage.results.pager;
      return pager.nextPage ? pager.page + 1 : undefined;
    },
    initialPageParam: 1,
  });
};

export const useInfiniteCategoryProductsData = (
  categoryUrl: string,
  params?: UseInfiniteProductsDataParams
) => {
  return useInfiniteQuery<ProductsResponse>({
    queryKey: ["infinite-category-products", categoryUrl, params],
    queryFn: ({ pageParam = 1 }) =>
      api.getCategoryProducts(categoryUrl, {
        ...params,
        page: pageParam as number,
      }),
    getNextPageParam: (lastPage) => {
      const pager = lastPage.results.pager;
      return pager.nextPage ? pager.page + 1 : undefined;
    },
    initialPageParam: 1,
  });
};
