#!/usr/bin/env bash
set -euo pipefail

# Test valid tool information
mise tool node | grep -q "Backend:" || fail "Backend field not found"

# Test JSON output
mise tool node --json | grep -q '"backend"' || fail "JSON backend field not found"

# Test specific field filters
backend_output=$(mise tool node --backend)
[[ -n $backend_output ]] || fail "Backend output is empty"

# Test that invalid tool names should error
assert_fail "mise tool INVALID_TOOL_NAME"

# Test duplicate version bug - install multiple versions of a tool
mise use tiny@1.0.0
mise use tiny@1.1.0
assert "mise tool tiny --installed" "1.0.0 1.1.0"

# Test security field exists in JSON output for aqua tool
mise tool aqua:cli/cli --json | jq -e '.security' || fail "security field not found in JSON"

# Test security field is an array
mise tool aqua:cli/cli --json | jq -e '.security | type == "array"' || fail "security is not an array"

# Test that security features have type field when present
mise tool aqua:cli/cli --json | jq -e '.security | if length > 0 then .[0].type else true end' || fail "security feature missing type field"

# Naming an aqua tool by its registry short name must reach the same package as spelling
# the backend out. Both are cli/cli; only the second form used to resolve, because the
# lookup went through the short name rather than the aqua package name.
# See https://github.com/jdx/mise/discussions/4917
short_desc=$(mise tool github-cli --description)
[[ -n $short_desc && $short_desc != "[none]" ]] || fail "short name should carry a description"
[[ $short_desc == "$(mise tool aqua:cli/cli --description)" ]] || fail "description differs by spelling"
[[ $(mise tool github-cli --json | jq -c '.security') == "$(mise tool aqua:cli/cli --json | jq -c '.security')" ]] || fail "security differs by spelling"

# Test core plugin security features
# Node has checksum + gpg
mise tool node --json | jq -e '.security | length >= 1' || fail "node should have security features"
mise tool node --json | jq -e '.security[] | select(.type == "checksum")' || fail "node should have checksum"

# Go has checksum
mise tool go --json | jq -e '.security[] | select(.type == "checksum")' || fail "go should have checksum"

# Zig has checksum + minisign
mise tool zig --json | jq -e '.security[] | select(.type == "checksum")' || fail "zig should have checksum"
mise tool zig --json | jq -e '.security[] | select(.type == "minisign")' || fail "zig should have minisign"
mise tool zig --json | jq -e '.security[] | select(.type == "minisign") | .public_key' || fail "zig minisign should have public_key"
