import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { QUERY_KEYS } from "@/utils/query-key";
import {
  getAdminNotifications,
  getAdminNotificationsUnread,
  getAdminNotificationsCount,
  markNotificationRead,
  markAllNotificationsRead,
} from "./_requests";
import { AdminNotificationsFilters } from "./_models";

export const useAdminNotifications = (filters?: AdminNotificationsFilters) => {
  return useQuery({
    queryKey: [QUERY_KEYS.GET_ADMIN_NOTIFICATIONS, filters],
    queryFn: () => getAdminNotifications(filters),
  });
};

export const useAdminNotificationsUnread = (limit?: number) => {
  return useQuery({
    queryKey: [QUERY_KEYS.GET_ADMIN_NOTIFICATIONS_UNREAD, limit],
    queryFn: () => getAdminNotificationsUnread(limit),
  });
};

export const useAdminNotificationsCount = () => {
  return useQuery({
    queryKey: [QUERY_KEYS.GET_ADMIN_NOTIFICATIONS_COUNT],
    queryFn: () => getAdminNotificationsCount(),
    refetchInterval: 30000,
  });
};

export const useMarkNotificationRead = () => {
  const queryClient = useQueryClient();
  
  return useMutation({
    mutationFn: (notificationId: number) => markNotificationRead(notificationId),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: [QUERY_KEYS.GET_ADMIN_NOTIFICATIONS] });
      queryClient.invalidateQueries({ queryKey: [QUERY_KEYS.GET_ADMIN_NOTIFICATIONS_UNREAD] });
      queryClient.invalidateQueries({ queryKey: [QUERY_KEYS.GET_ADMIN_NOTIFICATIONS_COUNT] });
    },
  });
};

export const useMarkAllNotificationsRead = () => {
  const queryClient = useQueryClient();
  
  return useMutation({
    mutationFn: () => markAllNotificationsRead(),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: [QUERY_KEYS.GET_ADMIN_NOTIFICATIONS] });
      queryClient.invalidateQueries({ queryKey: [QUERY_KEYS.GET_ADMIN_NOTIFICATIONS_UNREAD] });
      queryClient.invalidateQueries({ queryKey: [QUERY_KEYS.GET_ADMIN_NOTIFICATIONS_COUNT] });
    },
  });
};
