import S3UrlSignerService from './index';
import {
  axiosPutOptions,
  axiosGetBlobOptions,
} from '@services/s3urlsigner/config';
import {
  S3GetParams,
  S3PutParams,
  FetchFileReturnedValue,
} from '@interfaces/services/s3urlsigner';
import get from 'lodash/get';
import axios from 'axios';

class S3UrlSignerFilesService {
  public fetchFileFromS3ByUrl({
    url,
    options = {},
  }: S3GetParams): Promise<FetchFileReturnedValue> {
    return new Promise((resolve, reject) => {
      S3UrlSignerService.fetchSignedGetUrl({ url, options })
        .then((response) => {
          const presignedUrl = get(response, 'presignedUrl');
          const instance = axios.create();
          delete instance.defaults.headers.common.Authorization;
          instance
            .get(presignedUrl, axiosGetBlobOptions)
            .then((resp) => {
              resolve({
                presignedUrl,
                file: resp.data,
              });
            })
            .catch((e) => {
              reject(e);
            });
        })
        .catch((e) => {
          console.error(
            `[services/S3UrlSignerFilesService/fetchFileFromS3ByUrl] - ${e.toString()}`
          );
          reject(e);
        });
    });
  }

  public uploadFileToS3ByPath({
    file,
    path,
    options = {},
  }: S3PutParams): Promise<string | undefined> {
    return new Promise((resolve, reject) => {
      S3UrlSignerService.fetchSignedPutUrl({ path, options })
        .then((response) => {
          const instance = axios.create();
          delete instance.defaults.headers.common.Authorization;
          instance
            .put(get(response, 'presignedUrl'), file, axiosPutOptions)
            .then(() => resolve(get(response, 's3Url')))
            .catch((e) => reject(e));
        })
        .catch((e) => {
          console.error(
            `[services/S3UrlSignerFilesService/uploadFileToS3ByPath] - ${e.toString()}`
          );
          reject(e);
        });
    });
  }
}

export default new S3UrlSignerFilesService();
