import axios from 'axios';

let resourcePathsCache = null;
let cachedBaseUrl = null;

/**
 * Fetches a single resource path by name.
 *
 * @param {string} baseUrl - The base URL of the JSON:API server.
 * @param {string} entityType - The entity type (e.g., "node--article").
 * @returns {Promise<string>} - The resource path for the given name.
 */
export const getResourcePath = async (baseUrl, entityType) => {
  const resourcePaths = await getResourcePaths(baseUrl);

  if (resourcePaths[entityType]) {
    return resourcePaths[entityType];
  }

  throw new Error(`Resource path for ${entityType} not found in API response.`);
};

/**
 * Fetches and caches all resource paths from the /jsonapi endpoint.
 *
 * @param {string} baseUrl - The base URL of the JSON:API server.
 * @returns {Promise<Object>} - A mapping of resource types to their paths.
 */
export const getResourcePaths = async (baseUrl) => {
  // Return cached data if it exists for the same baseUrl.
  if (resourcePathsCache && cachedBaseUrl === baseUrl) {
    return resourcePathsCache;
  }

  console.log(`Fetching resource paths from ${baseUrl}`);

  const response = await axios.get(baseUrl);
  const links = response.data.links;

  // Extract resource paths from the "links" object.
  resourcePathsCache = Object.entries(links).reduce((acc, [key, value]) => {
    if (value.href) {
      acc[key] = value.href;
    }
    return acc;
  }, {});

  cachedBaseUrl = baseUrl;
  return resourcePathsCache;
};
