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


export const usePaths = (parent_id) => {
    const queryClient = useQueryClient();
    const config = useConfig();
    return useQuery({
        queryKey: ["paths", parent_id],
        queryFn: () => fetch_(`${config.BACKEND_HOST}/api/path/parent/${parent_id}`),
        enabled: !!parent_id,
        onSuccess: (data) => {
            if(data) {
                for (const pth of data)
                {
                    queryClient.setQueryData({queryKey: ["path", pth.id]}, pth);
                }
            }
        }
    });
};


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

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

    return useMutation({
        mutationFn: (data) => fetch_(`${config.BACKEND_HOST}/api/path/`, {
            method: "POST",
            body: JSON.stringify(data),
        }),
        onSuccess: (res) => {
            queryClient.invalidateQueries({queryKey: ["paths", res.parent_id]});
            queryClient.invalidateQueries({queryKey: ["tree"]});
        },
    });
};

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

    return useMutation({
        mutationFn: ({ id, data }) => fetch_(`${config.BACKEND_HOST}/api/path/${id}`, {
            method: "PATCH",
            body: JSON.stringify(data),
        }),
        onSuccess: (res) => {
            queryClient.invalidateQueries({queryKey: ["paths", res.parent_id]});
            queryClient.invalidateQueries({queryKey: ["path", res.id]});
            queryClient.invalidateQueries({queryKey: ["tree"]});
        },
    });
};

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

    return useMutation({
        mutationFn: (id) => fetch_(`${config.BACKEND_HOST}/api/path/${id}`, {
            method: "DELETE",
        }),
        onSuccess: () => {
            queryClient.invalidateQueries({queryKey: ["paths"]});
            queryClient.invalidateQueries({queryKey: ["tree"]});
        },
    });
};


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

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