import { useQuery, useQueryClient } from "@tanstack/react-query";
import { ServiceCategorySchema } from "@/lib/client";
import {
    getServiceCategoriesOptions,
    getServiceCategoriesQueryKey,
} from "@/lib/client/@tanstack/react-query.gen";

export type ServiceCategoriesList = {
    categories: ServiceCategorySchema[];
    setCategories: (categories: ServiceCategorySchema[]) => void;
    refetch: () => void;
    queryKey: any[];
    isLoading: boolean;
};

const useServiceCategoriesList = (): ServiceCategoriesList => {
    const queryClient = useQueryClient();
    const { data, refetch, isLoading } = useQuery(
        getServiceCategoriesOptions()
    );

    const queryKey = getServiceCategoriesQueryKey();

    const setCategories = (categories: ServiceCategorySchema[]) => {
        queryClient.setQueryData(
            queryKey,
            (old: { items: ServiceCategorySchema[] }) => ({
                ...old,
                items: categories,
            })
        );
    };

    return {
        categories: data?.items ?? [],
        setCategories,
        refetch,
        queryKey,
        isLoading,
    };
};

export default useServiceCategoriesList;
