import fetch from 'node-fetch';


const postApi = (url: any, body: any, token: any, apiKey: any) => {
  try{
    return new Promise((resolve, reject) => {
      console.info(`[INFO] start sync router at : ${new Date().getTime()}ms`);
      console.info(`body: ${JSON.stringify(body)}`);
      fetch(url, {
        method: 'POST',
        headers: token === null ?{
          'Content-Type': 'application/json',
          'x-api-key': apiKey
        }:{
          'Content-Type': 'application/json',
          'Authorization': `Bearer `.concat(token),
          'x-api-key': apiKey
        },
        body: JSON.stringify(body),
      })
          .then((response) => {
            return response.json();
          })
          .then((data) => {
            resolve(data);
          })
          .catch((error) => {
            reject(error);
          });

    });
  }catch (e){
    console.error(`[Error] request log: ${e}`);
  }
};

const putApi = (url: string, body: any, token: any) => {
  return new Promise((resolve, reject) => {
    fetch(url, {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`,
      },
      body: JSON.stringify(body),
    })
      .then((response) => {
        return response.json();
      })
      .then((data) => {
        resolve(data);
      })
      .catch((error) => {
        reject(error);
      });
  });
};

const deleteApi = (url: string, body: any, token: string) => {
  return new Promise((resolve, reject) => {
    fetch(url, {
      method: 'DELETE',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`,
      },
      body: JSON.stringify(body),
    })
      .then((response) => {
        return response.json();
      })
      .then((data) => {
        resolve(data);
      })
      .catch((error) => {
        reject(error);
      });
  });
};

export const getApi = (url: any, token: any) => {
  return new Promise(async (resolve, reject) => {
    await fetch(url, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`,
      },
    })
      .then((response) => {
        return response.json();
      })
      .then((data) => {
        resolve(data);
      })
      .catch((error) => {
        reject(error);
      });
  });
};

const API = {
  postApi,
  putApi,
  deleteApi,
  getApi,
};

export default API;
