// @ts-check
const log = require("@acanto/workflow-utils/log");
const chalk = require("@acanto/workflow-utils/chalk");
const https = require("https");
const axios = require("axios").default;

/**
 * @typedef {Object} APIRequestOpts
 * @property {string} [subject="data"]
 * @property {boolean} [useCache=false]
 */

const cache = {};

/**
 * Get API url
 *
 * @returns {string}
 */
function getApiUrl() {
  const { removeTrailingSlashes } = require("../utils");
  return removeTrailingSlashes(process.env.CMS_API_URL);
}

/**
 * API axios instance
 *
 * @type {import("axios").AxiosInstance}
 */
const api = axios.create({
  httpsAgent: new https.Agent({
    rejectUnauthorized: false,
  }),
});

/**
 * Get API data (from CMS)
 *
 * @param {string} endpoint
 * @param {APIRequestOpts} [customOptions]
 */
function getApiData(endpoint, customOptions) {
  const defaultOptions = {
    subject: "data",
    useCache: false,
  };
  let opts = {};
  if (customOptions) {
    opts = {
      ...defaultOptions,
      ...customOptions,
    };
  } else {
    opts = { ...defaultOptions };
  }
  const hasCache = opts.useCache && cache[endpoint];

  const url = `${getApiUrl()}${endpoint}`;

  if (hasCache) {
    // log(chalk.dim.italic(`Retrieving ${opts.subject} from CMS local cache.`));
    return cache[endpoint];
  }

  log(chalk.dim.italic(`Retrieving ${opts.subject} from CMS API ${url}...`));
  // @ts-ignore
  const promise = api.get(url);

  promise.then(
    () => {
      // log(chalk.italic.green.dim(`Successfully retrieved ${opts.subject}.`));
    },
    (error) => {
      log(chalk.italic.red(`Failed retrieving ${opts.subject}. Error:`), error);
    }
  );

  if (!hasCache) {
    cache[endpoint] = promise;
  }

  return promise;
}

module.exports = {
  getApiUrl,
  getApiData,
};
