/**
 * useNotifications Hook
 *
 * Custom hook for managing notifications with automatic polling
 * Polls the API every 30 seconds for new notifications
 */

'use client';

import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { listNotifications, markNotificationAsRead, markAllNotificationsAsRead } from '@/lib/api';
import type { NotificationResponse } from '@/types/api';

interface UseNotificationsOptions {
  /**
   * Whether to fetch only unread notifications
   * @default true
   */
  unreadOnly?: boolean;
  /**
   * Maximum number of notifications to fetch
   * @default 10
   */
  limit?: number;
  /**
   * Polling interval in milliseconds
   * @default 30000 (30 seconds)
   */
  refetchInterval?: number;
}

export function useNotifications(options: UseNotificationsOptions = {}) {
  const { unreadOnly = true, limit = 10, refetchInterval = 30000 } = options;

  const queryClient = useQueryClient();

  // Fetch notifications with automatic polling
  const { data, isLoading, refetch, error } = useQuery({
    queryKey: ['notifications', { isRead: !unreadOnly, limit }],
    queryFn: () => listNotifications({ isRead: !unreadOnly, limit }),
    refetchInterval, // Poll every 30 seconds by default
    refetchOnWindowFocus: true, // Refetch when window regains focus
  });

  const notifications = data?.notifications || [];
  const unreadCount = notifications.filter((n: NotificationResponse) => !n.read).length;

  // Mark single notification as read
  const markAsReadMutation = useMutation({
    mutationFn: markNotificationAsRead,
    onSuccess: () => {
      // Invalidate all notification queries to refetch
      queryClient.invalidateQueries({ queryKey: ['notifications'] });
    },
  });

  // Mark all notifications as read
  const markAllAsReadMutation = useMutation({
    mutationFn: markAllNotificationsAsRead,
    onSuccess: () => {
      // Invalidate all notification queries to refetch
      queryClient.invalidateQueries({ queryKey: ['notifications'] });
    },
  });

  /**
   * Mark a single notification as read
   * @param id - Notification ID
   */
  const markAsRead = async (id: string) => {
    return markAsReadMutation.mutateAsync(id);
  };

  /**
   * Mark all notifications as read
   */
  const markAllAsRead = async () => {
    return markAllAsReadMutation.mutateAsync();
  };

  /**
   * Manually refetch notifications
   */
  const refresh = () => {
    return refetch();
  };

  return {
    /** Array of notifications */
    notifications,
    /** Count of unread notifications */
    unreadCount,
    /** Mark a single notification as read */
    markAsRead,
    /** Mark all notifications as read */
    markAllAsRead,
    /** Manually refresh notifications */
    refresh,
    /** Loading state */
    isLoading,
    /** Error state */
    error,
    /** Whether marking as read is in progress */
    isMarkingAsRead: markAsReadMutation.isPending,
    /** Whether marking all as read is in progress */
    isMarkingAllAsRead: markAllAsReadMutation.isPending,
  };
}
