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

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

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


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


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

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