import { useQuery } from '@tanstack/react-query';
import { useIsAuthenticated } from '@/hooks';
import { notificationsApi } from '../apis';
import { notificationKeys } from '../keys';
import { UNREAD_COUNT_REFETCH_INTERVAL, UNREAD_COUNT_STALE_TIME } from '../constants';

/**
 * The **polled** unread count that drives the bell badge — stale-while-revalidate: the cached count is served
 * instantly, treated fresh for `UNREAD_COUNT_STALE_TIME`, refetched every `UNREAD_COUNT_REFETCH_INTERVAL` and
 * on window focus (background revalidation), so we never hammer the endpoint (phase §5). Gated on
 * authentication so the bell never polls for a signed-out user. Returns the raw count (0 while loading) so
 * only the bell — not the shell — re-renders on a change.
 */
export function useUnreadCount(): number {
  const isAuthenticated = useIsAuthenticated();
  const { data } = useQuery({
    queryKey: notificationKeys.unreadCount(),
    queryFn: () => notificationsApi.getUnreadCount(),
    enabled: isAuthenticated,
    staleTime: UNREAD_COUNT_STALE_TIME,
    refetchInterval: UNREAD_COUNT_REFETCH_INTERVAL,
    refetchOnWindowFocus: true,
  });
  return data ?? 0;
}
