import { useQuery, useQueryClient } from "@tanstack/react-query";
import { ProductSchema } from "@/lib/client";
import {
    getProductsOptions,
    getProductsQueryKey,
} from "@/lib/client/@tanstack/react-query.gen";

type Props = {
    searchInput: string;
    page?: number;
    itemsPerPage?: number;
};

const useProductsList = ({ searchInput, page, itemsPerPage }: Props) => {
    const queryClient = useQueryClient();
    const options = {
        query: { searchInput, page, itemsPerPage },
    };
    const { data, refetch, isLoading } = useQuery(getProductsOptions(options));

    const queryKey = getProductsQueryKey(options);

    const setProducts = (products: ProductSchema[]) => {
        queryClient.setQueryData(
            queryKey,
            (old: { items: ProductSchema[] }) => ({
                ...old,
                items: products,
            })
        );
    };

    return {
        products: data?.items ?? [],
        setProducts,
        refetch,
        queryKey,
        isLoading,
    };
};

export default useProductsList;
