import type { ImgHTMLAttributes } from 'react';

import { useResolvedAssetReadUrl } from '../hooks/useResolvedAssetReadUrl';

type ResolvedAssetImageProps = Omit<
  ImgHTMLAttributes<HTMLImageElement>,
  'src'
> & {
  src?: string | null;
  fallbackSrc?: string | null;
  refreshKey?: string | number | null;
};

export function ResolvedAssetImage({
  src,
  fallbackSrc,
  alt,
  refreshKey,
  ...rest
}: ResolvedAssetImageProps) {
  const { resolvedUrl } = useResolvedAssetReadUrl(src, {
    refreshKey,
  });
  const finalSrc = resolvedUrl || fallbackSrc?.trim() || '';

  if (!finalSrc) {
    return null;
  }

  return <img {...rest} src={finalSrc} alt={alt} />;
}
