import {useMemo} from 'react';
import {VideoSource} from 'expo-video';
import {useGetAuthHeaders} from '@hooks/useGetAuthHeaders';

/**
 * Builds the bearer-authenticated source object that both the chat tile
 * (`VideoRenderer`) and the gallery (`VideoPlayer`) feed into the
 * `VideoPlayerPool`.
 *
 * `useGetAuthHeaders` returns a freshly-allocated `{Authorization: ...}`
 * object on every render — plugging that into a memo dep would re-create
 * the source on every render, churning the pool (release/acquire faster
 * than React's effect ordering can settle the slot's refCount, so the
 * pool's idle-slot reuse never gets to fire). Memoizing on a serialized
 * fingerprint of the headers (a primitive, value-compared by React)
 * keeps the source identity stable for as long as the underlying token
 * doesn't actually change.
 */
export function useVideoSource(url: string | undefined): VideoSource {
  const isHttp = !!url && url.startsWith('http');
  const authHeaders = useGetAuthHeaders(isHttp);
  const authHeadersKey = authHeaders ? JSON.stringify(authHeaders) : '';
  return useMemo<VideoSource>(() => {
    if (!url) return null;
    // Local `file://` sources are already on disk; no caching needed (and
    // the cache config in `VideoPlayerPool` only governs remote bytes).
    if (!isHttp) return {uri: url};
    if (!authHeaders) return null;
    // `useCaching: true` opts THIS source into expo-video's shared
    // disk cache (sized in `VideoPlayerPool` via
    // `setVideoCacheSizeAsync`). Default is `false` — without this
    // flag the cache is never written to, so the same video re-fetches
    // every time you open the gallery. Caveat: not supported with HLS
    // on iOS or DRM (neither of which the chat uses).
    return {uri: url, headers: authHeaders, useCaching: true};
    // `authHeaders` is intentionally accessed via closure rather than
    // listed as a dep — its identity is unstable but its content is
    // captured by `authHeadersKey`.
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [url, isHttp, authHeadersKey]);
}
