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

export const useMarkdownPermissionSettings = () => {
    const config = useConfig();
    const queryClient = useQueryClient();
    return useQuery({
            queryKey: ["markdown_permission_settings"],
            queryFn: () => fetch_(`${config.BACKEND_HOST}/api/setting/markdown/permission/`),
            onSuccess: async (data) => {
                if (data) {
                    for (const setting of data) {
                        await queryClient.invalidateQueries(["markdown_permission_setting", setting.id]);
                    }
                }
            }
        }
    );
};

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

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

export const useUpdateMarkdownPermissionSetting = () => {
    const config = useConfig();
    const queryClient = useQueryClient();
    return useMutation(
        ({id, data}) => fetch_(`${config.BACKEND_HOST}/api/setting/markdown/permission/${id}`, {
            method: "PATCH",
            body: JSON.stringify(data),
        }),{
            onSuccess: (res) => {
                queryClient.invalidateQueries(["markdown_permission_setting", res.id]);
                queryClient.invalidateQueries(["markdown_permission_settings"]);
            }
        }
    );
};

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