import { DefaultApi, PresignedUrlResponse } from '@openapi/s3urlsigner';
import { configCreator } from './config';
import { AxiosResponse } from 'axios';
import {
  S3BaseParams,
  S3GetParams,
  S3PutParams,
} from '@interfaces/services/s3urlsigner';

class S3UrlSignerService {
  public fetchSignedDeleteUrl({
    url,
    region = undefined,
    options = {},
  }: S3BaseParams) {
    return new Promise((resolve, reject) => {
      configCreator().then((config) => {
        new DefaultApi(config)
          .getSignedDELETE(url, region, options)
          .then((response: AxiosResponse<PresignedUrlResponse>) => {
            resolve(response.data);
          })
          .catch((e) => {
            console.error(
              `[services/S3UrlSignerService/fetchSignedDeleteUrl] - ${e.toString()}`
            );
            reject(e);
          });
      });
    });
  }

  public fetchSignedGetUrl({
    url,
    fileName = undefined,
    region = undefined,
    options = {},
  }: S3GetParams) {
    return new Promise((resolve, reject) => {
      configCreator().then((config) => {
        new DefaultApi(config)
          .getSignedGET(url, fileName, region, options)
          .then((response: AxiosResponse<PresignedUrlResponse>) => {
            resolve(response.data);
          })
          .catch((e) => {
            console.error(
              `[services/S3UrlSignerService/fetchSignedGetUrl] - ${e.toString()}`
            );
            reject(e);
          });
      });
    });
  }

  public fetchSignedPutUrl({
    path,
    bucket,
    orgId = undefined,
    region = undefined,
    options = {},
  }: S3PutParams) {
    return new Promise((resolve, reject) => {
      configCreator().then((config) => {
        new DefaultApi(config)
          .getSignedPUTv3(path, orgId, bucket, region, options)
          .then((response: AxiosResponse<PresignedUrlResponse>) => {
            resolve(response.data);
          })
          .catch((e) => {
            console.error(
              `[services/S3UrlSignerService/fetchSignedDeleteUrl] - ${e.toString()}`
            );
            reject(e);
          });
      });
    });
  }
}

export default new S3UrlSignerService();
