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



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

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

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


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


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

            console.log("invalidateQueries: ", res.id, typeof res.id);
        },
    });
};


export const useMoveMarkdown = () => {
    const queryClient = useQueryClient();
    const config = useConfig();

    return useMutation({
        mutationFn: ({markdown, direction}) => {
            const apiEndpoint = `${config.BACKEND_HOST}/api/markdown/move_${direction}/${markdown.id}`;
            return fetch_(apiEndpoint, {method: "PATCH"});
        },
        onSuccess: () => {
            queryClient.invalidateQueries({queryKey: ["paths"]});
            queryClient.invalidateQueries({queryKey: ["tree"]});
        }
    });
};

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

export const useSearchMarkdown = (keyword) => {
    const config = useConfig();
    return useQuery({
        queryKey: ["markdownsByKeyword", keyword],
        queryFn: () => fetch_(
            `${config.BACKEND_HOST}/api/markdown/search/${encodeURIComponent(keyword)}`,
        ),
        enabled: !!keyword,
    });
};


export const useLinks = () => {
    const config = useConfig();
    return useQuery({
        queryKey: ["links"], 
        queryFn: () => fetch_(`${config.BACKEND_HOST}/api/markdown/links`)
    });
}
