#!/usr/bin/env bash

assert "mise set FOO=bar" ""
assert "mise set FOO" "bar"
assert "mise set" "FOO  bar ~/workdir/mise.toml"
assert "mise set --rm FOO" ""
assert_fail "mise set FOO" "Environment variable FOO not found"

assert "mise set --file .test.mise.toml FOO=bar" ""
assert "mise set --file .test.mise.toml FOO" "bar"

# Test -E flag for environment-specific config files
assert "mise set -E staging STAGING_VAR=staging_value" ""
assert "mise set -E staging STAGING_VAR" "staging_value"
assert "mise set -E staging" "STAGING_VAR  staging_value ~/workdir/mise.staging.toml"

# Test that -E flag only shows vars from that environment file
assert "mise set -E production PROD_VAR=prod_value" ""
assert "mise set -E production" "PROD_VAR  prod_value ~/workdir/mise.production.toml"
# STAGING_VAR should not appear when reading production env
assert_not_contains "mise set -E production" "STAGING_VAR"

# Test that regular set doesn't show env-specific vars
assert_not_contains "mise set" "STAGING_VAR"
assert_not_contains "mise set" "PROD_VAR"

# Test that mise set writes to mise.toml (lowest precedence) instead of mise.local.toml
# when both exist. See: https://github.com/jdx/mise/discussions/6475
rm -f mise.toml mise.local.toml
echo '[env]' >mise.toml
echo 'BASE_VAR = "base"' >>mise.toml
echo '[env]' >mise.local.toml
echo 'LOCAL_VAR = "local"' >>mise.local.toml
assert "mise set NEW_VAR=new_value" ""
assert_contains "cat mise.toml" "NEW_VAR"
assert_not_contains "cat mise.local.toml" "NEW_VAR"

# Test --stdin reads multiline value
assert "printf 'line1\nline2' | mise set --stdin MULTI_LINE" ""
assert "mise set MULTI_LINE" "line1
line2"
assert "mise set --rm MULTI_LINE" ""

# Test --stdin strips trailing newline
assert "printf 'hello\n' | mise set --stdin TRAILING_NL" ""
assert "mise set TRAILING_NL" "hello"
assert "mise set --rm TRAILING_NL" ""

# Test --stdin fails with multiple keys
assert_fail "printf 'val' | mise set --stdin KEY1 KEY2"

# Test --stdin fails with KEY=VALUE syntax
assert_fail "printf 'val' | mise set --stdin KEY1=value"
