import {useMemo} from 'react';
import {File} from 'expo-file-system';
import {VideoAsset} from '@modules/chats/interfaces';
import {useAttachmentData} from '@modules/chats/store/zustand/useAttachments';
import {isVideoAsset} from '@modules/chats/utils';

/**
 * Picks the best playback URL for a video attachment:
 *
 *  - If a local `file://` URI is registered for this asset AND the file
 *    actually exists on disk → return the local path. This is the case
 *    for videos the user just sent (the source file is still on the
 *    device) or, rarely, videos that FileHandler previously persisted.
 *    expo-video plays local files without any network round-trip.
 *  - Otherwise → return the remote `video_url`. expo-video streams +
 *    caches via its own disk cache.
 *
 * The `File.exists` check is synchronous, so this can run inside a
 * `useMemo` without an effect/state dance.
 */
export function useVideoFileUrl(
  messageId: string,
  assetId: number,
): string | undefined {
  const fileData = useAttachmentData(messageId, assetId);
  const asset = fileData?.asset;
  const localUri = fileData?.uri;

  return useMemo(() => {
    if (!asset || !isVideoAsset(asset)) return undefined;
    if (localUri && localUri.startsWith('file://')) {
      try {
        if (new File(localUri).exists) return localUri;
      } catch {
        /* fall through to remote */
      }
    }
    return (asset as VideoAsset).video_url;
  }, [asset, localUri]);
}
