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

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

type ReturnType = {
    products: ProductSchema[];
    paginationInfo?: PaginationInfoSchema;
    setProducts: (products: ProductSchema[]) => void;
    refetch: () => void;
    queryKey: any[];
    isLoading: boolean;
};

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

    const queryKey = getProductsQueryKey(options);

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

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

export default useProductsList;
