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



export const useMarkdown = (id) => {
    const config = useConfig();
    return useQuery(
        ["markdown", id],
        () => fetch_(`${config.BACKEND_HOST}/api/markdown/${id}`),
        {
            enabled: !!id,
        });
};

export const useIndexMarkdown = (path_id) => {
    const queryClient = useQueryClient();
    const config = useConfig();
    return useQuery(
        ["index_markdown", path_id],
        () => fetch_(`${config.BACKEND_HOST}/api/markdown/get_index/${path_id}`),{
            enabled: !!path_id,
            onSuccess: (data) => {
                if(data && data.id){
                    queryClient.setQueryData(["markdown", data.id], data);
                }
            }
        });
};

export const useHomeMarkdown = () => {
    const queryClient = useQueryClient();
    const config = useConfig();
    return useQuery(
        ["home_markdown"],
        () => fetch_(`${config.BACKEND_HOST}/api/markdown/get_home`), {
            onSuccess: (data) => {
                if (data && data.id){
                    queryClient.setQueryData(["markdown", data.id], data);
                }
            }
        });
};


export const useMarkdownsByPath = (pathId) => {
    const config = useConfig();
    return useQuery(
        ["markdownsByPath", pathId],
        () => fetch_(`${config.BACKEND_HOST}/api/markdown/by_path/${pathId}`),
        {
            enabled: !!pathId
        });
};

export const useSaveMarkdown = () => {
    const queryClient = useQueryClient();
    const config = useConfig();
    return useMutation(({id, data}) => {
        const url = id
            ? `${config.BACKEND_HOST}/api/markdown/${id}`
            : `${config.BACKEND_HOST}/api/markdown/`;
        const method = id ? "PUT" : "POST";
        return fetch_(url, {
            method,
            body: JSON.stringify(data),
        })
    },{
        onSuccess: (res, variables) => {
            queryClient.invalidateQueries(["markdownsByPath", variables.data.parent_id]);
            queryClient.invalidateQueries(["markdown", variables.data.id]);
        },
    });
};


