import S3UrlSignerFilesService from '@services/s3urlsigner/files';
import { saveAs } from 'file-saver';
import { saveFileViaLink } from '@utils/files';
import { notifyError } from '@utils/notify';
import get from 'lodash/get';

export async function fetchDocumentAttachment(
  document: any,
  mode = 'preview',
  nameField = 'file.name',
  urlField = 'file.url'
): Promise<{ file?: Blob; presignedUrl?: string }> {
  try {
    const fileName = get(document, nameField) || 'Безымянный';
    const url = get(document, urlField);

    if (!url) return {};

    const {
      file,
      presignedUrl,
    } = await S3UrlSignerFilesService.fetchFileFromS3ByUrl({ url });

    switch (mode) {
      case 'download': {
        saveAs(file, fileName);
        break;
      }
      case 'preview': {
        saveFileViaLink({
          anchor: new HTMLAnchorElement(),
          hrefData: presignedUrl,
          fileName,
          target: '_blank',
        });
        break;
      }
    }
    return { file, presignedUrl };
  } catch (e) {
    notifyError('Возникла проблема при скачивания файла');
    console.log('fetch-document-attachments | ERROR -> ', e);
    return {};
  }
}
