#!/usr/bin/env bash

# Test `mise lock --bump`: re-resolves fuzzy version selectors against the
# latest matching remote versions without installing anything and without
# modifying config files. Also tests the `--json` change report.

export MISE_LOCKFILE=1

reset_lockfile() {
  cat <<'EOF' >mise.lock
# @generated - this file is auto-generated by `mise lock` https://mise.jdx.dev/dev-tools/mise-lock.html

[[tools.dummy]]
version = "1.0.0"
backend = "asdf:dummy"
EOF
}

echo "=== Setup: prefix selector locked at an old version ==="
cat <<'EOF' >mise.toml
[tools]
dummy = "1"
EOF
reset_lockfile

echo "=== Without --bump, lock keeps the locked version ==="
mise lock --platform linux-x64
assert_contains "cat mise.lock" 'version = "1.0.0"'

echo "=== --bump re-resolves the selector to the latest matching version ==="
mise lock --bump --platform linux-x64
assert_contains "cat mise.lock" 'version = "1.1.0"'
assert_not_contains "cat mise.lock" 'version = "1.0.0"'
# config selector is left untouched
assert_contains "cat mise.toml" 'dummy = "1"'

echo "=== --bump --dry-run --json reports changes without writing ==="
reset_lockfile
assert_contains "mise lock --bump --dry-run --json --platform linux-x64" '"name": "dummy"'
assert_contains "mise lock --bump --dry-run --json --platform linux-x64" '"1.0.0"'
assert_contains "mise lock --bump --dry-run --json --platform linux-x64" '"1.1.0"'
assert_contains "cat mise.lock" 'version = "1.0.0"'

echo "=== --bump --json writes and reports ==="
mise lock --bump --json --platform linux-x64
assert_contains "cat mise.lock" 'version = "1.1.0"'
# a second run has nothing to change
assert "mise lock --bump --json --platform linux-x64" "[]"

echo "=== 'latest' selector bumps to the latest version ==="
cat <<'EOF' >mise.toml
[tools]
dummy = "latest"
EOF
reset_lockfile
mise lock --bump --platform linux-x64
assert_contains "cat mise.lock" 'version = "2.0.0"'

echo "=== exactly pinned versions are not bumped ==="
cat <<'EOF' >mise.toml
[tools]
dummy = "1.0.0"
EOF
reset_lockfile
assert "mise lock --bump --json --platform linux-x64" "[]"
assert_contains "cat mise.lock" 'version = "1.0.0"'
assert_contains "cat mise.toml" 'dummy = "1.0.0"'

echo "=== --bump never rewrites config, even with explicit tool@version ==="
cat <<'EOF' >mise.toml
[tools]
dummy = "1"
EOF
reset_lockfile
mise lock --bump dummy@2 --platform linux-x64
assert_contains "cat mise.toml" 'dummy = "1"'
# without --bump the same invocation bumps the config prefix
mise lock dummy@2.0.0 --platform linux-x64
assert_contains "cat mise.toml" 'dummy = "2"'

echo "=== tools removed from config are reported as pruned in --json ==="
cat <<'EOF' >mise.toml
[tools]
dummy = "1"
EOF
reset_lockfile
mise lock --bump --platform linux-x64
cat <<'EOF' >mise.toml
[tools]
EOF
assert_contains "mise lock --json --platform linux-x64" '"new_versions": []'
assert_not_contains "cat mise.lock" 'tools.dummy'
