import { API_ENDPOINTS } from "@/lib/api";
import { notificationService } from "@/lib/api/services/notification-service";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useMemo } from "react";
import { toast } from "react-toastify";

export const useGetNotificationHistoryQuery = (
  params?: Record<string, any>,
  options?: { enabled: boolean },
) => {
  const queryKey = useMemo(
    () => [API_ENDPOINTS.NOTIFICATIONS.HISTORY, params],
    [params],
  );
  return useQuery({
    queryKey,
    queryFn: () => notificationService.getNotifications(params),
    ...options,
  });
};
export const useGetMyNotifications = (params?: Record<string, any>) => {
  const queryKey = useMemo(
    () => [API_ENDPOINTS.NOTIFICATIONS.MY_NOTIFICATIONS, params],
    [params],
  );
  return useQuery({
    queryKey,
    queryFn: () => notificationService.getMyNotifications(params),
  });
};
export const useMarkNotificationAsSeen = (successCallback?: () => void) => {
  const queryClient = useQueryClient();
  return useMutation({
    mutationKey: ["MARK_NOTIFICATION_AS_SEEN"],
    mutationFn: (id: string) => notificationService.markNotificationAsSeen(id),
    onSuccess: () => {
      if (successCallback) {
        successCallback();
      }
      queryClient.invalidateQueries({
        queryKey: [API_ENDPOINTS.NOTIFICATIONS.MY_NOTIFICATIONS],
      });
    },
  });
};
export const useGetNotificationDetails = (id: string) => {
  const queryKey = useMemo(
    () => [API_ENDPOINTS.NOTIFICATIONS.DETAILS(id), "NOTIFICATION DETAILS"],
    [id],
  );
  return useQuery({
    queryKey,
    queryFn: () => notificationService.getNotificationDetails(id),
  });
};
export const useCreateNotificationQuery = (successCallback?: () => void) => {
  const queryClient = useQueryClient();
  const mutationKey = useMemo(
    () => [API_ENDPOINTS.NOTIFICATIONS.CREATE, "CREATE NOTIFICATION"],
    [],
  );
  return useMutation({
    mutationKey,
    mutationFn: notificationService.createNotification,
    onSuccess: ({ message }: { message: string }) => {
      toast.success(message);
      queryClient.invalidateQueries({
        queryKey: [API_ENDPOINTS.NOTIFICATIONS.HISTORY],
      });
      queryClient.invalidateQueries({
        queryKey: [API_ENDPOINTS.NOTIFICATIONS.MY_NOTIFICATIONS],
      });
      if (successCallback) {
        successCallback();
      }
    },
  });
};
