import S3UrlSignerService from './index';
import {
  getAxiosPutOptions,
  getAxiosGetBlobOptions,
} from '@/recruits/services/s3UrlService/config';
import {
  S3GetParams,
  S3PutParams,
  FetchFileReturnedValue,
} from '@/recruits/interfaces/s3UrlService';
import axios from 'axios';

class S3UrlSignerFilesService {
  public async fetchFileFromS3ByUrl({
    url,
    responseType,
    options = {},
  }: S3GetParams): Promise<FetchFileReturnedValue> {
    try {
      const { presignedUrl } = await S3UrlSignerService.fetchSignedUrlForGet({
        url,
        options,
      });
      if (!presignedUrl) throw new Error('Не удалось получить presignedUrl');
      const instance = axios.create();
      delete instance.defaults.headers.common.Authorization;
      const { data: file } = await instance.get(
        presignedUrl,
        getAxiosGetBlobOptions(responseType)
      );

      return {
        presignedUrl,
        file,
      };
    } catch (e) {
      console.error(
        `[services/S3UrlSignerFilesService/fetchFileFromS3ByUrl] - ${e}`
      );
      throw e;
    }
  }

  public async uploadFileToS3ByPath({
    file,
    path,
    bucket,
    contentType,
    options = {},
  }: S3PutParams): Promise<string | undefined> {
    try {
      const {
        presignedUrl,
        s3Url,
      } = await S3UrlSignerService.fetchSignedUrlForPut({
        path,
        bucket,
        options,
      });
      if (!presignedUrl) throw new Error('Не удалось получить presignedUrl');
      const instance = axios.create();
      delete instance.defaults.headers.common.Authorization;
      await instance.put(presignedUrl, file, getAxiosPutOptions(contentType));
      return s3Url;
    } catch (e) {
      console.error(
        `[services/S3UrlSignerFilesService/uploadFileToS3ByPath] - ${e}`
      );
      throw e;
    }
  }
}

export default new S3UrlSignerFilesService();
