import { useQuery, useQueryClient } from "@tanstack/react-query";
import { ServiceSchema } from "@/lib/client";
import {
    getServicesOptions,
    getServicesQueryKey,
} from "@/lib/client/@tanstack/react-query.gen";

export type ServicesList = {
    services: ServiceSchema[];
    setServices: (services: ServiceSchema[]) => void;
    refetch: () => void;
    queryKey: any[];
    isLoading: boolean;
};

const useServicesList = (): ServicesList => {
    const queryClient = useQueryClient();
    const { data, refetch, isLoading } = useQuery(getServicesOptions());

    const queryKey = getServicesQueryKey();

    const setServices = (services: ServiceSchema[]) => {
        queryClient.setQueryData(
            queryKey,
            (old: { items: ServiceSchema[] }) => ({
                ...old,
                items: services,
            })
        );
    };

    return {
        services: data?.items ?? [],
        setServices,
        refetch,
        queryKey,
        isLoading,
    };
};

export default useServicesList;
