/* COPYRIGHT Esri - https://js.arcgis.com/1.2/LICENSE.txt */
import { w as prepareDataForSolutionDisplay } from "./interfaces.js";
import { getItemRelatedItems } from "@esri/solution-common";
async function getRelatedSolutionsInfos(userSession, card) {
  const templateInfos = await processTemplates(card, userSession);
  let uniqueIitemIds = [];
  let _nonSolutionDependencyItems = [];
  let multiSolutionDependencies = [];
  const dependencyFetches = templateInfos.map(async (template) => {
    const relatedItems = await _getRelatedDependency(template.id, "reverse", "Solution2Item", userSession);
    return { template, relatedItems };
  });
  const resolvedDependencies = await Promise.all(dependencyFetches);
  for (const { template, relatedItems } of resolvedDependencies) {
    for (const relatedItem of relatedItems) {
      const solutionItemDeps = [];
      for (const itemId of relatedItem.relatedItemIds) {
        solutionItemDeps.push({
          controlItemId: template.id,
          dependencyItemId: itemId
        });
      }
      const grouped = solutionItemDeps.reduce((acc, dep) => {
        if (!acc[dep.controlItemId]) {
          acc[dep.controlItemId] = /* @__PURE__ */ new Set();
        }
        acc[dep.controlItemId].add(dep.dependencyItemId);
        return acc;
      }, {});
      const uniqueFiltered = Object.entries(grouped).filter(([_, depSet]) => depSet.size > 1).flatMap(
        ([controlItemId, depSet]) => Array.from(depSet).map((dependencyItemId) => ({
          controlItemId,
          dependencyItemId
        }))
      );
      if (uniqueFiltered.length > 0) {
        multiSolutionDependencies = multiSolutionDependencies.concat(uniqueFiltered);
      }
    }
  }
  _nonSolutionDependencyItems = Array.from(
    new Map(
      [
        ...multiSolutionDependencies
      ].map((dep) => [`${dep.controlItemId}:${dep.dependencyItemId}`, dep])
    ).values()
  );
  const controlItems = _nonSolutionDependencyItems.map((dep) => dep.controlItemId);
  uniqueIitemIds = [...new Set(controlItems)];
  return {
    uniqueIitemIds,
    _nonSolutionDependencyItems,
    templateInfos
  };
}
async function _getRelatedDependency(itemId, direction, type, userSession) {
  const relatedItems = await getItemRelatedItems(itemId, type, direction, userSession);
  return [{
    relationshipType: type,
    relatedItemIds: relatedItems.relatedItems.map((item) => item.id)
  }];
}
async function processTemplates(card, userSession) {
  return await prepareDataForSolutionDisplay(card.id, userSession);
}
export {
  getRelatedSolutionsInfos as g,
  processTemplates as p
};
