/**
 * @ai-summary Hook for in-app notifications with real-time count
 * @ai-context Provides notification list and unread count with polling
 */

import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { useAuth0 } from '@auth0/auth0-react';
import { notificationsApi } from '../api/notifications.api';
import type { UserNotification, UnreadNotificationCount } from '../types/notifications.types';

export function useInAppNotifications() {
  const { isAuthenticated } = useAuth0();
  const queryClient = useQueryClient();

  // Unread count - polls every 60 seconds
  const countQuery = useQuery<UnreadNotificationCount>({
    queryKey: ['notificationCount'],
    queryFn: notificationsApi.getUnreadCount,
    enabled: isAuthenticated,
    refetchInterval: 60 * 1000, // Poll every minute
    staleTime: 30 * 1000,
  });

  // Notification list
  const listQuery = useQuery<UserNotification[]>({
    queryKey: ['inAppNotifications'],
    queryFn: () => notificationsApi.getInAppNotifications(20, false),
    enabled: isAuthenticated,
    staleTime: 60 * 1000,
  });

  // Mark as read mutation
  const markAsReadMutation = useMutation({
    mutationFn: notificationsApi.markAsRead,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['notificationCount'] });
      queryClient.invalidateQueries({ queryKey: ['inAppNotifications'] });
    },
  });

  // Mark all as read mutation
  const markAllAsReadMutation = useMutation({
    mutationFn: notificationsApi.markAllAsRead,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['notificationCount'] });
      queryClient.invalidateQueries({ queryKey: ['inAppNotifications'] });
    },
  });

  // Delete mutation
  const deleteMutation = useMutation({
    mutationFn: notificationsApi.deleteNotification,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['notificationCount'] });
      queryClient.invalidateQueries({ queryKey: ['inAppNotifications'] });
    },
  });

  return {
    notifications: listQuery.data ?? [],
    unreadCount: countQuery.data?.total ?? 0,
    countByType: countQuery.data,
    isLoading: listQuery.isLoading || countQuery.isLoading,
    isError: listQuery.isError || countQuery.isError,
    markAsRead: markAsReadMutation.mutateAsync,
    markAllAsRead: markAllAsReadMutation.mutateAsync,
    deleteNotification: deleteMutation.mutateAsync,
    refetch: () => {
      queryClient.invalidateQueries({ queryKey: ['notificationCount'] });
      queryClient.invalidateQueries({ queryKey: ['inAppNotifications'] });
    },
  };
}
