const fs = require('fs-extra');
const paths = require('./paths');

/**
 * Current project config cache.
 *
 * @type {Record<string, any> | undefined}
 */
let projectConfig;
/**
 * @type {Promise<Record<string, any>>}
 */
let readProjectConfigPromise;

/**
 * Reads project's config only once.
 *
 * @return {Promise<Record<string, any>>}
 */
function readProjectConfig() {
  if (!readProjectConfigPromise) {
    readProjectConfigPromise = (async () => {
      await fs.access(paths.config, fs.constants.R_OK);
      const data = await fs.readFile(paths.config, 'utf8');

      const jsonData = JSON.parse(data);
      projectConfig = jsonData;

      return jsonData;
    })();
  }

  return readProjectConfigPromise;
}

/**
 * Returns project's config.
 *
 * @return {Record<string, any>}
 */
function getProjectConfig() {
  if (!projectConfig) {
    throw new Error('Project config is not loaded. Please use reactProjectConfig first.');
  }

  return projectConfig;
}

module.exports = {
  readProjectConfig,
  getProjectConfig,
};
