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

export const usePatches = (markdownId) => {
    const config = useConfig();
    return useQuery({
        queryKey: ["patches", markdownId],
        queryFn: () =>
            fetch_(`${config.BACKEND_HOST}/api/patch/by_markdown/${markdownId}`),
        enabled: !!markdownId,
    });
};

export const useCreatePatch = () => {
    const queryClient = useQueryClient();
    const config = useConfig();
    return useMutation({
        mutationFn: (data) =>
            fetch_(`${config.BACKEND_HOST}/api/patch/`, {
                method: "POST",
                body: JSON.stringify(data),
            }),
        onSuccess: (res) => {
            queryClient.invalidateQueries({
                queryKey: ["patches", res.markdown_id],
            });
        },
    });
};

export const useUpdatePatch = () => {
    const queryClient = useQueryClient();
    const config = useConfig();
    return useMutation({
        mutationFn: ({ id, data }) =>
            fetch_(`${config.BACKEND_HOST}/api/patch/${id}`, {
                method: "PATCH",
                body: JSON.stringify(data),
            }),
        onSuccess: (res) => {
            queryClient.invalidateQueries({
                queryKey: ["patches", res.markdown_id],
            });
        },
    });
};

export const useDeletePatch = () => {
    const queryClient = useQueryClient();
    const config = useConfig();
    return useMutation({
        mutationFn: ({ id }) =>
            fetch_(`${config.BACKEND_HOST}/api/patch/${id}`, {
                method: "DELETE",
            }),
        onSuccess: (_res, { markdownId }) => {
            queryClient.invalidateQueries({ queryKey: ["patches", markdownId] });
        },
    });
};
