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

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

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


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

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

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