#!/usr/bin/env bash

# Tests for `mise lock` with `tool@latest` and poisoned "latest" lockfiles.
# Regression coverage for bugs where:
#   - `mise lock tool@latest` wrote the literal string "latest" to the lockfile
#     instead of resolving it to a concrete installed version.
#   - `mise lock tool` (or `mise lock`) with a lockfile that already held
#     `version = "latest"` produced a duplicate entry alongside the concrete
#     installed version.

export MISE_LOCKFILE=1

cat <<'EOF' >mise.toml
[tools]
tiny = "latest"
EOF
mise uninstall tiny --all 2>/dev/null || true
mise install tiny@3.0.0
mise install tiny@3.1.0

# ------------------------------------------------------------------
# `mise lock tool@latest` must resolve to the newest installed
# concrete version, never write the literal "latest".
# ------------------------------------------------------------------
cat <<'EOF' >mise.lock
# @generated
[[tools.tiny]]
version = "3.0.0"
EOF
mise lock tiny@latest --platform linux-x64
assert_contains "cat mise.lock" 'version = "3.1.0"'
assert_not_contains "cat mise.lock" 'version = "latest"'
assert_not_contains "cat mise.lock" 'version = "3.0.0"'

# ------------------------------------------------------------------
# A poisoned lockfile containing `version = "latest"` must be cleaned up
# on a single `mise lock` run and replaced with the concrete version,
# never producing a duplicate entry.
# ------------------------------------------------------------------
cat <<'EOF' >mise.lock
# @generated
[[tools.tiny]]
version = "latest"
EOF
mise lock tiny --platform linux-x64
assert_contains "cat mise.lock" 'version = "3.1.0"'
assert_not_contains "cat mise.lock" 'version = "latest"'
# There should be exactly one [[tools.tiny]] entry.
assert "[ \"$(grep -c '^\[\[tools.tiny\]\]' mise.lock)\" = \"1\" ]"

# ------------------------------------------------------------------
# Refresh semantics: `mise lock tool` with a valid lockfile must
# preserve the current version (not introduce a newer one via the
# "latest" fallback).
# ------------------------------------------------------------------
cat <<'EOF' >mise.lock
# @generated
[[tools.tiny]]
version = "3.0.0"
EOF
mise lock tiny --platform linux-x64
assert_contains "cat mise.lock" 'version = "3.0.0"'
assert_not_contains "cat mise.lock" 'version = "3.1.0"'
assert "[ \"$(grep -c '^\[\[tools.tiny\]\]' mise.lock)\" = \"1\" ]"

rm -f mise.toml mise.lock
unset MISE_LOCKFILE
