/**
 * Pure derivation of reply / forward preview metadata from a message's
 * `attachments`. Used by `<ChatReply>` and `<MessageItem>`'s reply
 * block to decide whether to render a thumbnail preview and where to
 * pull its URL from.
 *
 * No FileHandler involvement — images and video posters go through
 * ExpoImage with `withAuthHeader + enableCache`, so the consumer just
 * needs the remote URL (sized via `getChatImage.addSize`).
 *
 * Was a `usePreviewAsset` hook; promoted to a plain function because
 * it has no React state / effects.
 */
import {Asset, VideoAsset} from '../interfaces';
import {
  isDocumentAsset,
  isVideoAsset,
  mapAssetToUrl,
} from './mappers/assetMapper';

const SHOW_PREVIEW_FORMATS = ['video', 'image'];

interface Params {
  assets?: Asset[];
}

export const getPreviewAsset = ({assets}: Params) => {
  const asset = assets?.[0];
  const hasAttachment = !!assets?.length;
  const isMultipleAttachments = hasAttachment && (assets?.length ?? 0) > 1;
  const isVideo = !!asset && isVideoAsset(asset);
  const isFile = !!asset && isDocumentAsset(asset);
  // Reply previews only render for SINGLE image / video attachments.
  // Multi-attachment messages fall back to the prefix-icon text row
  // because there's no good thumb to show.
  const showPreview =
    hasAttachment &&
    !isMultipleAttachments &&
    SHOW_PREVIEW_FORMATS.includes(asset?.metadata?.format ?? '');

  return {
    showPreview,
    attachment: {
      asset,
      isVideo,
      // Remote URL — `getChatImage.addSize` + ExpoImage handle sizing
      // + caching downstream.
      url: asset ? mapAssetToUrl(asset) ?? '' : '',
      thumbnailUrl: isVideo ? (asset as VideoAsset).thumbnail_url : undefined,
    },
    hasAttachment,
    isFile,
  };
};
