import { useEffect } from 'react';

import { router } from '@inertiajs/react';

/**
 * Polls the server by reloading specific Inertia props at regular intervals
 * when a condition is met (e.g., job is pending/processing).
 *
 * @param shouldPoll - Boolean condition that determines if polling should be active
 * @param intervalMs - Polling interval in milliseconds
 * @param reloadKeys - Array of Inertia prop keys to reload
 *
 * @example
 * const { polling_interval_ms } = usePage<PageProps>().props;
 * usePolling(
 *   ['pending', 'processing'].includes(job.status),
 *   polling_interval_ms,
 *   ['job', 'results']
 * );
 */
export function usePolling(shouldPoll: boolean, intervalMs: number, reloadKeys: string[]) {
  useEffect(() => {
    if (shouldPoll) {
      const interval = setInterval(() => {
        router.reload({ only: reloadKeys });
      }, intervalMs);
      return () => clearInterval(interval);
    }
  }, [shouldPoll, intervalMs, reloadKeys]);
}
