import axiosInstance from "@/lib/axios";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";

const FetchLatestNotifications = async () => {
  const { data } = await axiosInstance.get(`/notifications/latest`);
  return data;
};

const markNotificationAsRead = async (id: string) => {
  const { data } = await axiosInstance.post(
    `/notifications/mark-as-read/${id}`
  );

  return data;
};

const clearNotifications = async (id: string[]) => {
  const { data } = await axiosInstance.post(`/notifications/clear`, {
    notification_ids: id,
  });

  return data;
};

export const useClearNotifications = () => {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: (id: string[]) => {
      const response = clearNotifications(id);
      return response;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({
        queryKey: ["Notifications"],
        refetchType: "active",
      });
    },
    onError: (error) => {
      console.error("Error Marking notification as read:", error);
      return error;
    },
  });
};

export const useClearNotification = () => {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: (id: string[]) => {
      const response = clearNotifications(id);
      return response;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({
        queryKey: ["Notifications"],
        refetchType: "active",
      });
    },
    onError: (error) => {
      console.error("Error Marking notification as read:", error);
      return error;
    },
  });
};

export const useMarkNotificationRead = () => {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: (id: string) => {
      const response = markNotificationAsRead(id);
      return response;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({
        queryKey: ["Notifications"],
        refetchType: "active",
      });
    },
    onError: (error) => {
      console.error("Error Marking notification as read:", error);
      return error;
    },
  });
};

export const useGetLatestNotifications = () => {
  return useQuery({
    queryKey: ["Notifications"],
    queryFn: FetchLatestNotifications,
    staleTime: 0,
    refetchOnWindowFocus: "always",
  });
};
