"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.disableGlobalGraphQLErrorHandling = disableGlobalGraphQLErrorHandling;
exports.default = API;
exports.API_URL = exports.API_HOST = exports.PRODUCTION_API_HOST = void 0;

var _nodeFetch = _interopRequireDefault(require("node-fetch"));

var _core = require("@apollo/client/core");

var _error = require("@apollo/client/link/error");

var _chalk = _interopRequireDefault(require("chalk"));

var _token = _interopRequireDefault(require("./token"));

var _env = _interopRequireDefault(require("./env"));

var _socksProxyAgent = _interopRequireDefault(require("./http/socks-proxy-agent"));

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

/**
 * 
 * @format
 */

/**
 * External dependencies
 */

/**
 * Internal dependencies
 */
// Config
const PRODUCTION_API_HOST = 'https://api.wpvip.com';
exports.PRODUCTION_API_HOST = PRODUCTION_API_HOST;
const API_HOST = process.env.API_HOST || PRODUCTION_API_HOST;
exports.API_HOST = API_HOST;
const API_URL = `${API_HOST}/graphql`;
exports.API_URL = API_URL;
let globalGraphQLErrorHandlingEnabled = true;

function disableGlobalGraphQLErrorHandling() {
  globalGraphQLErrorHandlingEnabled = false;
}

async function API() {
  const token = await _token.default.get();
  const headers = {
    Authorization: token ? `Bearer ${token.raw}` : null,
    'User-Agent': _env.default.userAgent
  };
  const errorLink = (0, _error.onError)(({
    networkError,
    graphQLErrors
  }) => {
    if (networkError && networkError.statusCode === 401) {
      console.error(_chalk.default.red('Unauthorized:'), 'You are unauthorized to perform this request, please logout with `vip logout` then try again.');
      process.exit();
    }

    if (graphQLErrors && graphQLErrors.length && globalGraphQLErrorHandlingEnabled) {
      graphQLErrors.forEach(error => {
        console.error(_chalk.default.red('Error:'), error.message);
      });
      process.exit();
    }
  });
  const proxyAgent = (0, _socksProxyAgent.default)();
  const httpLink = new _core.HttpLink({
    uri: API_URL,
    headers,
    fetch: _nodeFetch.default,
    fetchOptions: {
      agent: proxyAgent
    }
  });
  const apiClient = new _core.ApolloClient({
    link: errorLink.concat(httpLink),
    cache: new _core.InMemoryCache()
  });
  /**
   * Call the Public API with an arbitrary path (e.g. to connect to REST endpoints).
   * This will include the token in an Authorization header so requests are "logged-in."
   * @param {string} path API path to pass to `fetch` -- will be prefixed by the API_HOST
   * @param {object} options options to pass to `fetch`
   * @returns {Promise} Return value of the `fetch` call
   */

  apiClient.apiFetch = (path, options = {}) => (0, _nodeFetch.default)(`${API_HOST}${path}`, { ...options,
    ...{
      agent: proxyAgent,
      headers: { ...headers,
        ...{
          'Content-Type': 'application/json'
        },
        ...options.headers
      }
    },
    ...{
      body: typeof options.body === 'object' ? JSON.stringify(options.body) : options.body
    }
  });

  return apiClient;
}