'use strict';

const Axios = require('axios');

class API {
  constructor(data = {}) {
    // todo change to custom domain
    this.root = 'https://69502mswbk.execute-api.us-east-1.amazonaws.com';
    this.org = data.org;
  }

  authorize(org) {
    this.org = org;
  }

  async request(options) {
    const requestOptions = {
      url: `${this.root}${options.endpoint}`,
      method: options.method || 'POST',
      headers: {
        'Authorization': `Bearer ${this.org.accessKey}`,
        'Content-Type': 'application/json',
      },
      data: options.body,
    };

    if (options.headers) {
      requestOptions.headers = { ...requestOptions.headers, ...options.headers };
    }

    const axios = Axios.create();

    axios.defaults.headers.common = {};
    axios.defaults.headers.put = {};

    try {
      const res = await axios(requestOptions);
      return res.data;
    } catch (error) {
      // Add useful details if they are included in the HTTP response
      if (error.response && error.response.data) {
        const err = new Error(error.response.data.message);
        err.statusCode = error.response.data.statusCode || error.response.status || null;
        err.name = error.response.data.name || null;
        err.details = error.response.data.details || null;
        err.url = error.response.config.url || null;
        throw err;
      }

      // otherwise, throw the typical axios error
      throw error;
    }
  }
}

module.exports = API;
