#!/usr/bin/env bash

export MISE_EXPERIMENTAL=1

rm -rf "$MISE_DATA_DIR/plugins/tiny"
ln -s "$ROOT/test/data/plugins/tiny" "$MISE_DATA_DIR/plugins/tiny"

# a global request that the repository overrides must not leak into the union
mkdir -p "$HOME/.config/mise"
cat >"$HOME/.config/mise/config.toml" <<'TOML'
[tools]
tiny = "1.0.0"
TOML

mkdir -p monorepo/child monorepo/sibling
cat >monorepo/mise.toml <<'TOML'
monorepo_root = true

[monorepo]
config_roots = [".", "child", "sibling"]

[tools]
tiny = "2.1.0"
TOML
touch monorepo/child/mise.toml
cat >monorepo/sibling/mise.toml <<'TOML'
[tools]
tiny = "3.1.0"
TOML

# the empty child inherits the root's pin, not the global one; the sibling's
# override still contributes its own version
assert "cd monorepo && mise ls --current --monorepo tiny --json | jq -r '[.[].version] | sort | join(\",\")'" "2.1.0,3.1.0"

# an undeclared directory under the root is not an ancestor of child, so its
# config must not leak into child's hierarchy
mkdir -p monorepo/scratch
cat >monorepo/scratch/mise.toml <<'TOML'
[tools]
tiny = "3.0.1"
TOML
assert "cd monorepo/scratch && mise ls --current --monorepo tiny --json | jq -r '[.[].version] | sort | join(\",\")'" "2.1.0,3.1.0"

# an intermediate directory between the root and a nested config root
mkdir -p monorepo/packages/app
cat >monorepo/packages/mise.toml <<'TOML'
[tools]
tiny = "3.0.1"
TOML
touch monorepo/packages/app/mise.toml
cat >monorepo/mise.toml <<'TOML'
monorepo_root = true

[monorepo]
config_roots = [".", "child", "sibling", "packages/app"]

[tools]
tiny = "2.1.0"
TOML
assert "cd monorepo && mise ls --current --monorepo tiny --json | jq -r '[.[].version] | sort | join(\",\")'" "2.1.0,3.0.1,3.1.0"
