package sandbox

import (
	"os/exec"
	"runtime"
	"testing"

	"github.com/stretchr/testify/require"
)

func TestNew_NoneAlwaysNoop(t *testing.T) {
	sb := New(ModeNone)
	require.IsType(t, noopSandbox{}, sb)
}

func TestNew_UnsupportedPlatformFallsBackToNoop(t *testing.T) {
	if runtime.GOOS == "linux" {
		t.Skip("uid/container are supported on linux; this asserts the non-linux fallback")
	}
	// On non-linux, uid/container must fall back to no-op so dev/CI never break.
	require.IsType(t, noopSandbox{}, New(ModeUID))
	require.IsType(t, noopSandbox{}, New(ModeContainer))
}

func TestNoopSandbox_MutatesNothing(t *testing.T) {
	cmd := exec.Command("echo", "hi")
	before := cmd.SysProcAttr
	cleanup, err := noopSandbox{}.Apply(cmd, Spec{Mode: ModeNone, ProxyURL: "http://proxy:8080"})
	require.NoError(t, err)
	require.NotNil(t, cleanup)
	// no-op must NOT inject proxy env nor touch SysProcAttr.
	require.Equal(t, before, cmd.SysProcAttr)
	require.Empty(t, cmd.Env)
	// cleanup is safe to call.
	cleanup()
}

func TestInjectProxyEnv(t *testing.T) {
	cmd := exec.Command("echo", "hi")
	cmd.Env = []string{"PATH=/usr/bin"}
	injectProxyEnv(cmd, Spec{ProxyURL: "http://proxy:3128"})
	require.Contains(t, cmd.Env, "HTTP_PROXY=http://proxy:3128")
	require.Contains(t, cmd.Env, "HTTPS_PROXY=http://proxy:3128")
	require.Contains(t, cmd.Env, "NO_PROXY=localhost,127.0.0.1,::1")
	// original env preserved.
	require.Contains(t, cmd.Env, "PATH=/usr/bin")
}

func TestInjectProxyEnv_NoProxyURLIsNoop(t *testing.T) {
	cmd := exec.Command("echo", "hi")
	injectProxyEnv(cmd, Spec{})
	require.Empty(t, cmd.Env)
}

func TestInjectProxyEnv_CustomNoProxy(t *testing.T) {
	cmd := exec.Command("echo", "hi")
	injectProxyEnv(cmd, Spec{ProxyURL: "http://p", NoProxy: "internal.local"})
	require.Contains(t, cmd.Env, "NO_PROXY=internal.local")
}
