import { useQuery } from 'react-query';

import { getBlobCloudfrontDocument, isSecureFile } from 'src/utils/documents';
import { getBlobUrl } from 'src/utils/files';

type UseGetDocumentUrlProps = {
  source?: string;
};

const getDocumentUrl = async (source?: string) => {
  if (!source) return '';
  if (isSecureFile(source)) {
    const blob = await getBlobCloudfrontDocument(source);
    return getBlobUrl(blob) || '';
  }
  return source;
};

const useGetDocumentUrl = ({ source }: UseGetDocumentUrlProps) => {
  return useQuery<string>({
    queryKey: ['document-url', source],
    queryFn: () => getDocumentUrl(source),
    enabled: !!source,
  });
};

export default useGetDocumentUrl;
