#!/usr/bin/env bash

# Test that tool-level postinstall hooks fire when installing with an explicit
# version on the CLI (e.g. `mise install dummy@latest`).
# Regression test for https://github.com/jdx/mise/discussions/7979

cat <<EOF >mise.toml
[tools]
dummy = { version = "latest", postinstall = "echo POSTINSTALL_RAN=yes" }
EOF

# Remove any existing dummy installation to force reinstall
rm -rf "$MISE_DATA_DIR/installs/dummy"

# Test 1: Install with explicit CLI version — postinstall should still fire
output=$(mise install dummy@latest 2>&1)

if [[ $output == *"POSTINSTALL_RAN=yes"* ]]; then
  echo "✓ postinstall ran with explicit CLI version"
else
  echo "✗ postinstall did NOT run with explicit CLI version"
  echo "Output: $output"
  exit 1
fi

# Test 2: Existing runtime options must not prevent config options from merging
rm -rf "$MISE_DATA_DIR/installs/dummy"

output=$(mise install 'dummy[foo=bar]@latest' 2>&1)

if [[ $output == *"POSTINSTALL_RAN=yes"* ]]; then
  echo "✓ postinstall ran with explicit CLI and backend options"
else
  echo "✗ postinstall did NOT run with explicit CLI and backend options"
  echo "Output: $output"
  exit 1
fi

# Clean up and test again without explicit version to confirm it still works
rm -rf "$MISE_DATA_DIR/installs/dummy"

output=$(mise install dummy 2>&1)

if [[ $output == *"POSTINSTALL_RAN=yes"* ]]; then
  echo "✓ postinstall ran without explicit CLI version"
else
  echo "✗ postinstall did NOT run without explicit CLI version"
  echo "Output: $output"
  exit 1
fi

cat <<EOF >mise.toml
[tools]
dummy = [
  { version = "2.0.0", postinstall = "echo WRONG_POSTINSTALL=yes" },
  { version = "1.0.0", postinstall = "echo MATCHED_POSTINSTALL=yes" },
  { version = "1.1.0", postinstall = "echo MATCHED_POSTINSTALL=yes" },
]
EOF

# Test 4: An explicit install selects options from its matching configured version
status=0
output=$(mise install dummy@1.0.0 2>&1) || status=$?

if [[ $status -eq 0 && $output == *"MATCHED_POSTINSTALL=yes"* && $output != *"WRONG_POSTINSTALL=yes"* ]]; then
  echo "✓ install used options from its matching configured version"
else
  echo "✗ install used options from the wrong configured version"
  echo "Status: $status"
  echo "Output: $output"
  exit 1
fi

# Test 5: The exec builder applies the same matching policy
status=0
output=$(mise x dummy@1.1.0 -- dummy 2>&1) || status=$?

if [[ $status -eq 0 && $output == *"MATCHED_POSTINSTALL=yes"* && $output != *"WRONG_POSTINSTALL=yes"* ]]; then
  echo "✓ exec used options from its matching configured version"
else
  echo "✗ exec used options from the wrong configured version"
  echo "Status: $status"
  echo "Output: $output"
  exit 1
fi
