#!/usr/bin/env bash

# Test that npm backend properly uses npm.package_manager settings

export MISE_INSTALL_BEFORE=1d

# Ensure npm is available by installing node if needed
if ! command -v npm >/dev/null 2>&1; then
	echo "npm not available in test environment, installing node..."
	# Disable GPG verification for faster test
	export MISE_GPG_VERIFY=false
	assert_succeed "mise use node@20"
fi

# Ensure bun is available
if ! command -v bun >/dev/null 2>&1; then
	echo "bun not available in test environment, installing..."
	assert_succeed "mise use bun@latest"
fi

# Ensure pnpm is available
if ! command -v pnpm >/dev/null 2>&1; then
	echo "pnpm not available in test environment, installing..."
	# Install pnpm using corepack or npm if needed, or just use mise
	assert_succeed "mise use pnpm@latest"
fi

# Test 1: Default behavior (npm) - checks npm.package_manager="npm" implicitly
echo "Testing npm backend with default settings (npm)..."
unset MISE_NPM_BUN
unset MISE_NPM_PACKAGE_MANAGER

# Test listing versions - should succeed
assert_succeed "mise ls-remote npm:tiny >/dev/null"
echo "✓ npm backend lists versions using npm"

# Test installation using npm (default)
mise uninstall npm:tiny@latest >/dev/null 2>&1 || true
assert_succeed "MISE_DEBUG=1 mise install npm:tiny@latest >/tmp/npm_debug.log 2>&1"
assert_contains "cat /tmp/npm_debug.log" "--before"
echo "✓ npm backend successfully installs package using npm (default)"
mise uninstall npm:tiny@latest >/dev/null 2>&1 || true

# Test 2: npm.package_manager = "bun"
echo "Testing npm.package_manager=bun..."
export MISE_NPM_PACKAGE_MANAGER=bun

assert_succeed "MISE_DEBUG=1 mise install npm:tiny@latest >/tmp/bun_debug.log 2>&1"
assert_contains "cat /tmp/bun_debug.log" "--minimum-release-age"
echo "✓ npm backend successfully installs package using bun (package_manager=bun)"
mise uninstall npm:tiny@latest >/dev/null 2>&1 || true

# Test 3: npm.package_manager = "pnpm"
echo "Testing npm.package_manager=pnpm..."
export MISE_NPM_PACKAGE_MANAGER=pnpm

if ! MISE_DEBUG=1 mise install npm:tiny@latest >/tmp/pnpm_debug.log 2>&1; then
	echo "Command failed. Output:"
	cat /tmp/pnpm_debug.log
	exit 1
fi
assert_contains "cat /tmp/pnpm_debug.log" "--config.minimumReleaseAge="
echo "✓ npm backend successfully installs package using pnpm (package_manager=pnpm)"
mise uninstall npm:tiny@latest >/dev/null 2>&1 || true

unset MISE_NPM_PACKAGE_MANAGER

echo "✓ npm package manager behavior test completed"
