import {useMutation, useQueryClient} from "react-query";
import {useAuthContext} from "@/contexts/AuthContext";
import firestore from "@react-native-firebase/firestore";
import {Notification} from "@/hooks/firebase/useGetNotifications";

export const useDeleteNotification = () => {
    const queryClient = useQueryClient();
    const {user} = useAuthContext();

    return useMutation({
        mutationFn: async (id: string) => {
            await firestore()
                .collection("Notifications")
                .doc(id)
                .delete();
        },
        onMutate: async (deletedId) => {
            await queryClient.cancelQueries(["notifications", user?.uid]);

            const previousNotifications = queryClient.getQueryData<Notification[]>(["notifications", user?.uid]);

            queryClient.setQueryData<Notification[]>(["notifications", user?.uid], (old) =>
                old?.filter((notification) => notification?.id! !== deletedId) ?? []
            );

            return {previousNotifications};
        },
        onError: (_err, _deletedId, context) => {
            if (context?.previousNotifications) {
                queryClient.setQueryData(["notifications", user?.uid], context.previousNotifications);
            }
        },
        onSettled: () => {
            queryClient.invalidateQueries(["notifications", user?.uid]);
        },
    });
};