import {useConfig} from "../../ConfigProvider";
import {useMutation, useQuery, useQueryClient} from "@tanstack/react-query";
import {fetch_} from "../request-utils";

export const usePathSettings = () => {
    const config = useConfig();
    const queryClient = useQueryClient();
    return useQuery({
        queryKey: ["path_settings"],
        queryFn: () => fetch_(`${config.BACKEND_HOST}/api/setting/path/`),
        onSuccess: (data) => {
            if(data){
                for(const setting of data)
                    queryClient.setQueryData({queryKey: ["path_setting", setting.id]}, setting);
            }
        }
    });
};

export const usePathSetting = (setting_id) => {
    const config = useConfig();
    return useQuery({
        queryKey: ["path_setting", setting_id],
        queryFn: () => fetch_(`${config.BACKEND_HOST}/api/setting/path/${setting_id}`),
        enabled: !!setting_id,
    });
};

export const useCreatePathSetting = () => {
    const config = useConfig();
    const queryClient = useQueryClient();
    return useMutation({
        mutationFn: (data) => fetch_(`${config.BACKEND_HOST}/api/setting/path/`, {
            method: "POST",
            body: JSON.stringify(data)
        }),
        onSuccess: (data) => {
            queryClient.invalidateQueries({queryKey: ["path_setting", data.id]});
            queryClient.invalidateQueries({queryKey: ["path_settings"]});
        }
    });
};


export const useUpdatePathSetting = () => {
    const config = useConfig();
    const queryClient = useQueryClient();
    return useMutation({
        mutationFn: ({id, data}) => fetch_(`${config.BACKEND_HOST}/api/setting/path/${id}`, {
            method: "PATCH",
            body: JSON.stringify(data)
        }),
        onSuccess: (data, variables) => {
            queryClient.invalidateQueries({queryKey: ["path_setting", variables.id]});
            queryClient.invalidateQueries({queryKey: ["path_settings"]});
        }
    });
};


export const useDeletePathSetting = () => {
    const config = useConfig();
    const queryClient = useQueryClient();
    return useMutation({
        mutationFn: (id) => fetch_(`${config.BACKEND_HOST}/api/setting/path/${id}`, {
            method: "DELETE",
        }),
        onSuccess: (data, variables) => {
            queryClient.invalidateQueries({queryKey: ["path_setting", variables.id]});
            queryClient.invalidateQueries({queryKey: ["path_settings"]});
        }
    });
};
