#!/usr/bin/env bash

# Test that if a lockfile is a symlink, that updating the lockfile keeps the symlink intact.

export MISE_LOCKFILE=1

# Create base config
cat >mise.toml <<'EOF'
[tools]
tiny = "1"
EOF

# Create a lockfile that is a symlink to another file.
# Put it into a subdirectory to ensure that mise correctly resolves the symlink
# target when updating from a different directory.
mkdir example-dotfiles
touch example-dotfiles/real-mise.lock
ln -s example-dotfiles/real-mise.lock mise.lock

# Install tools
assert "mise install tiny@1.0.0"

# Use the tools to trigger lockfile updates
assert "mise use tiny@1"

# Verify that the lockfile is still a symlink
assert "[[ -L mise.lock ]] && [[ $(readlink mise.lock) == example-dotfiles/real-mise.lock ]]"

# Base tool should be in mise.lock
assert_contains "cat mise.lock" "[[tools.tiny]]"
assert_contains "cat mise.lock" 'version = "1.0.0"'

# Verify that updating from a subdirectory also resolves the symlink target correctly
mkdir -p subdir
( # Use subshell to avoid having to cd back (SC2103)
	cd subdir

	# Using a new version to ensure the lockfile is updated
	assert "mise install tiny@2.1.0"
	assert "mise use tiny@2"
)

assert "[[ -L mise.lock ]] && [[ $(readlink mise.lock) == example-dotfiles/real-mise.lock ]]"
assert_contains "cat mise.lock" "[[tools.tiny]]"
assert_contains "cat mise.lock" 'version = "2.1.0"'

# Finally, let's test a dangling symlink scenario where the target file is deleted.

# Remove the real lockfile, leaving a dangling symlink
rm example-dotfiles/real-mise.lock

# Attempt to update the lockfile.
# This will overwrite the symlink with a new regular file since the target is missing.
assert "mise lock"

# Verify that the lockfile is no longer a symlink (since the target was missing)
assert "[[ ! -L mise.lock ]]"
assert_contains "cat mise.lock" "[[tools.tiny]]"
assert_contains "cat mise.lock" 'version = "2.1.0"'
