import { useQueryClient } from "@tanstack/react-query";
import { AxiosError } from "axios";
import { HttpValidationError } from "@/lib/client";
import { notifications } from "@/lib/notifications";

type Props = {
    key: string;
    queryKey: any[];
};

const getCommonQueryClient = ({ key, queryKey }: Props) => {
    const queryClient = useQueryClient();

    const onError = (
        error: AxiosError<HttpValidationError>,
        _: any,
        context: any
    ) => {
        console.error(error);
        notifications.error({
            message: error.response?.data?.detail as string | undefined,
        });
        if (context?.previous) {
            queryClient.setQueryData(queryKey, context.previous);
        }
    };

    const onSettled = () => {
        queryClient.invalidateQueries({
            predicate: (query: { queryKey: any }) =>
                query.queryKey[0]?._id === key,
        });
    };

    return { queryClient, onError, onSettled };
};

export default getCommonQueryClient;
