/**
 * Check if a core library exists in the current project
 *
 * @returns {string | false} Return `false` if it does not exist and its path if it does
 */
function coreLibraryExists(suffix = "") {
  const fs = require("fs");
  const coreLibraryPath = getCoreLibraryPath(suffix);

  if (fs.existsSync(coreLibraryPath)) {
    return coreLibraryPath;
  }
  return false;
}

/**
 * Get core library path (either it exists or not)
 * @returns {string}
 */
function getCoreLibraryPath(suffix = "") {
  const paths = require("../paths");
  const { coreLibrary } = require("../config");

  return paths.join(paths.root, "/node_modules/", coreLibrary + suffix);
}

/**
 * Get core library pacakge.json
 * @returns {{ name: string, version: string, config: { "core-sync"?: string[] } }}
 */
function getCoreLibraryPkg() {
  const paths = require("../paths");

  return require(paths.join(getCoreLibraryPath(), "/package.json"));
}

/**
 * Resolves the core library's node_modules path following symlink's real path
 * so that we can use `npm link` without problems
 *
 * @returns {string | false} Return `false` if it does not exist and its path if it does
 */
function getCoreLibraryNodeModulesPath(suffix = "") {
  const fs = require("fs");
  const path = require("path");
  const coreLibraryPath = coreLibraryExists(suffix);

  if (coreLibraryPath) {
    try {
      return fs.realpathSync(path.join(coreLibraryPath, "node_modules"));
    } catch (e) {
      return false;
    }
  }
  return false;
}

module.exports = {
  coreLibraryExists,
  getCoreLibraryPath,
  getCoreLibraryPkg,
  getCoreLibraryNodeModulesPath,
};
