/**
 * Hook to subscribe to navigation-aware request cancellation.
 *
 * Returns an AbortSignal that is automatically aborted when the user
 * navigates to a different route. Use this signal to cancel API requests
 * that are specific to the current route and should not survive a navigation.
 *
 * Usage:
 *   const signal = useNavigationAbortSignal();
 *   const { items } = useListData({
 *     fetcher: (sig) => fetchBans(sig || signal),
 *     // ...
 *   });
 *
 * For background tasks that should survive navigation:
 *   const signal = useNavigationAbortSignal({ ignoreCancellation: true });
 *
 * When to use:
 * - For page-level data fetches that should not persist across navigation
 * - For user-initiated refetches on the current page
 * - For paginated lists, search results, filters
 *
 * When NOT to use:
 * - For long-lived background polls (use ignoreCancellation: true instead)
 * - For service-level state syncs (e.g., session validation)
 * - For actions that may take longer than a user interaction timeout
 *
 * Note: The signal may already be aborted at the time you check it,
 * depending on timing. This is safe — fetchers should handle aborted
 * signals gracefully by throwing/catching AbortError.
 */

import { useContext } from "react";
import { NavigationCancellationContext } from "../providers/NavigationCancellationContext";
import type { GetNavigationSignalOptions } from "../providers/NavigationCancellationContext";

/**
 * Get an AbortSignal for the current route's request lifecycle.
 *
 * The returned signal will be aborted when the user navigates away.
 * All requests using this signal will be automatically cancelled.
 *
 * @param options - Optional configuration
 * @param options.ignoreCancellation - If true, the signal will not be
 *   aborted on navigation. Use for background tasks that should survive
 *   route changes.
 *
 * @returns AbortSignal tied to the current route
 * @throws Error if called outside NavigationCancellationProvider
 */
export function useNavigationAbortSignal(
  options?: GetNavigationSignalOptions,
): AbortSignal {
  const context = useContext(NavigationCancellationContext);

  if (!context) {
    throw new Error(
      "useNavigationAbortSignal must be used within NavigationCancellationProvider. " +
        "Wrap your router with <NavigationCancellationProvider> in App.tsx.",
    );
  }

  return context.getNavigationSignal(options);
}
