import { api } from '../constants/config';
import http from '../utils/fetch';

export async function getSignature() {
  return http.get(api.signature);
}

export async function uploadAssets(data, signal) {
  return http.upload(api.assetsUpload, data, { signal });
}

export async function deleteAssets({ type, fileList }) {
  return http.post(api.assetsDelete, {
    type,
    fileList
  });
}

export async function uploadAssetsToOSS({ signature, key, file, signal }) {
  signature = signature ? signature : await http.get(api.signature);
  if (signature) {
    const formData = new FormData();
    formData.append('key', key);
    formData.append('policy', signature.policy);
    formData.append('OSSAccessKeyId', signature.accessid);
    formData.append('success_action_status', '200');
    formData.append('signature', signature.signature);
    formData.append('file', file);
    return fetch(signature.host, {
      method: 'POST',
      body: formData,
      signal
    })
      .then((response) => response)
      .catch((error) => {
        console.error(error);
        return;
      });
  }
}

export async function uploadAssetsToLocal({ key, file, signal }) {
  const formData = new FormData();
  formData.append('key', key);
  formData.append('file', file);
  return http.upload(api.assetsUpload, formData, { signal });
}
