// src/lib/updo/resolveVersions.ts
import semver from "semver";
function computeWanted(info, ranges) {
  const candidates = ranges.map((range) => semver.maxSatisfying(info.versions, range));
  const valid = candidates.filter((v) => v !== null);
  if (valid.length === 0) return void 0;
  let min = valid[0];
  for (const v of valid) {
    if (semver.lt(v, min)) min = v;
  }
  return min;
}
function hasNewerVersion(version, current) {
  return version !== void 0 && semver.gt(version, current);
}
function isUpdateAvailable(current, wanted, latest, next) {
  if (!current) return false;
  return hasNewerVersion(wanted, current) || hasNewerVersion(latest, current) || hasNewerVersion(next, current);
}
function resolveVersions(deps, registry, installedVersions) {
  const resolved = [];
  for (const [name, dep] of deps) {
    const info = registry.get(name);
    const current = installedVersions.get(name);
    const wanted = info ? computeWanted(info, dep.ranges) : void 0;
    const latest = info?.distTags.latest;
    const rawNext = info?.distTags.next ?? info?.distTags.rc;
    const next = rawNext && latest && semver.gt(rawNext, latest) ? rawNext : void 0;
    const updateAvailable = isUpdateAvailable(current, wanted, latest, next);
    resolved.push({
      current,
      declaredRange: dep.ranges.length === 1 ? dep.ranges[0] : dep.ranges.join(" | "),
      depTypes: dep.depTypes,
      latest,
      name,
      next,
      updateAvailable,
      wanted: wanted && current && wanted !== current ? wanted : void 0,
      workspaces: dep.workspaces
    });
  }
  return resolved.toSorted((a, b) => {
    if (a.updateAvailable !== b.updateAvailable) return a.updateAvailable ? -1 : 1;
    return a.name.localeCompare(b.name);
  });
}
export {
  resolveVersions
};
//# sourceMappingURL=resolveVersions.mjs.map