import { useEffect } from 'react';
import { preload } from 'react-dom';
import { useQueryClient } from '@tanstack/react-query';
import type { Particle } from '@/api/types';
import { apiClient } from '@/api/client';

// TODO: verify that caching is actually working by slowing down our network to simulate
/**
 * Prefetches download URLs and warms the browser cache for adjacent media particles.
 */
export function usePrefetchAdjacentMedia(
  children: Particle[],
  currentIndex: number,
) {
  const queryClient = useQueryClient();

  useEffect(() => {
    const adjacentIndices = [currentIndex - 1, currentIndex + 1];
    const mediaParticles = adjacentIndices
      .filter((i) => i >= 0 && i < children.length)
      .map((i) => children[i])
      .filter(
        (p): p is Extract<Particle, { type: 'media' }> => p.type === 'media',
      );

    for (const particle of mediaParticles) {
      const objectId = particle.properties.object_id;

      queryClient
        .prefetchQuery({
          queryKey: ['download-url', objectId],
          queryFn: () => apiClient.getParticleDownloadUrl(objectId),
          staleTime: 1000 * 60 * 60,
        })
        .then(() => {
          const url = queryClient.getQueryData<string>([
            'download-url',
            objectId,
          ]);
          if (url) {
            preload(url, { as: 'fetch', crossOrigin: 'anonymous' });
          }
        });
    }
  }, [children, currentIndex, queryClient]);
}
