package paths

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

func TestCompanionBinaryPathPrefersEnv(t *testing.T) {
	t.Setenv("BANGER_VSOCK_AGENT_BIN", "/tmp/custom-vsock-agent")

	got, err := CompanionBinaryPath("banger-vsock-agent")
	if err != nil {
		t.Fatalf("CompanionBinaryPath: %v", err)
	}
	if got != "/tmp/custom-vsock-agent" {
		t.Fatalf("CompanionBinaryPath() = %q", got)
	}
}

func TestCompanionBinaryPathUsesSiblingBinary(t *testing.T) {
	root := t.TempDir()
	companion := filepath.Join(root, "banger-vsock-agent")
	if err := os.WriteFile(companion, []byte("test"), 0o755); err != nil {
		t.Fatalf("write companion: %v", err)
	}

	origExecutablePath := executablePath
	executablePath = func() (string, error) {
		return filepath.Join(root, "banger"), nil
	}
	t.Cleanup(func() {
		executablePath = origExecutablePath
	})

	got, err := CompanionBinaryPath("banger-vsock-agent")
	if err != nil {
		t.Fatalf("CompanionBinaryPath: %v", err)
	}
	if got != companion {
		t.Fatalf("CompanionBinaryPath() = %q, want %q", got, companion)
	}
}

func TestCompanionBinaryPathUsesInstalledLibDir(t *testing.T) {
	root := t.TempDir()
	companion := filepath.Join(root, "lib", "banger", "banger-vsock-agent")
	if err := os.MkdirAll(filepath.Dir(companion), 0o755); err != nil {
		t.Fatalf("mkdir companion dir: %v", err)
	}
	if err := os.WriteFile(companion, []byte("test"), 0o755); err != nil {
		t.Fatalf("write companion: %v", err)
	}

	origExecutablePath := executablePath
	executablePath = func() (string, error) {
		return filepath.Join(root, "bin", "banger"), nil
	}
	t.Cleanup(func() {
		executablePath = origExecutablePath
	})

	got, err := CompanionBinaryPath("banger-vsock-agent")
	if err != nil {
		t.Fatalf("CompanionBinaryPath: %v", err)
	}
	if got != companion {
		t.Fatalf("CompanionBinaryPath() = %q, want %q", got, companion)
	}
}
