package plugins

import (
	"os"
	"path/filepath"
	"runtime"
	"strings"
	"testing"
)

func TestSanitizedPluginEnvironmentDropsApplicationSecrets(t *testing.T) {
	t.Setenv("DATABASE_URL", "mysql://secret")
	t.Setenv("GO_LICENSE_KEY_FILE", "secret.key")
	environment := strings.Join(sanitizedPluginEnvironment(), "\n")
	if strings.Contains(environment, "DATABASE_URL=") || strings.Contains(environment, "GO_LICENSE_KEY_FILE=") {
		t.Fatalf("sensitive environment leaked to plugin: %s", environment)
	}
}

func TestSecureProcessEntryRejectsDirectoryEscape(t *testing.T) {
	root := t.TempDir()
	outside := filepath.Join(t.TempDir(), "plugin")
	if runtime.GOOS == "windows" {
		outside += ".exe"
	}
	if err := os.WriteFile(outside, []byte("test"), 0o755); err != nil {
		t.Fatal(err)
	}
	manifest := Manifest{
		ID: "escape", Name: "Escape", Version: "1", Runtime: RuntimeProcess,
		Dir: root, Entry: map[string]string{"default": outside},
	}
	if _, _, err := secureProcessEntry(manifest); err == nil {
		t.Fatal("expected entry outside plugin directory to be rejected")
	}
}

func TestBoundedBufferCapsOutput(t *testing.T) {
	buffer := newBoundedBuffer(4)
	input := []byte("12345678")
	written, err := buffer.Write(input)
	if err != nil || written != len(input) {
		t.Fatalf("Write() = %d, %v", written, err)
	}
	if got := buffer.String(); got != "1234" || !buffer.overflow {
		t.Fatalf("buffer = %q, overflow = %v", got, buffer.overflow)
	}
}
