package agenthttp

import (
	"testing"

	"zlh-agent/internal/state"
)

func TestEnsureDevCodeServerInstallsAndStartsWhenRequested(t *testing.T) {
	restoreCodeServerTestHooks(t)

	cfg := &state.Config{
		ContainerType:    "dev",
		Runtime:          "node",
		EnableCodeServer: true,
	}

	installed := false
	running := false
	installCalls := 0
	startCalls := 0
	verifyCalls := 0

	codeServerInstalled = func() bool { return installed }
	codeServerRunning = func() bool { return running }
	codeServerInstall = func(state.Config) error {
		installCalls++
		installed = true
		return nil
	}
	codeServerStart = func(state.Config) error {
		startCalls++
		running = true
		return nil
	}
	codeServerVerify = func() error {
		verifyCalls++
		return nil
	}

	if err := ensureDevCodeServer(cfg); err != nil {
		t.Fatalf("ensureDevCodeServer: %v", err)
	}
	if installCalls != 1 {
		t.Fatalf("installCalls = %d, want 1", installCalls)
	}
	if startCalls != 1 {
		t.Fatalf("startCalls = %d, want 1", startCalls)
	}
	if verifyCalls != 1 {
		t.Fatalf("verifyCalls = %d, want 1", verifyCalls)
	}
}

func TestEnsureDevCodeServerStartsInstalledStoppedAddon(t *testing.T) {
	restoreCodeServerTestHooks(t)

	cfg := &state.Config{
		ContainerType: "dev",
		Runtime:       "node",
		Addons:        []string{"codeserver"},
	}

	running := false
	installCalls := 0
	startCalls := 0

	codeServerInstalled = func() bool { return true }
	codeServerRunning = func() bool { return running }
	codeServerInstall = func(state.Config) error {
		installCalls++
		return nil
	}
	codeServerStart = func(state.Config) error {
		startCalls++
		running = true
		return nil
	}
	codeServerVerify = func() error { return nil }

	if err := ensureDevCodeServer(cfg); err != nil {
		t.Fatalf("ensureDevCodeServer: %v", err)
	}
	if installCalls != 0 {
		t.Fatalf("installCalls = %d, want 0", installCalls)
	}
	if startCalls != 1 {
		t.Fatalf("startCalls = %d, want 1", startCalls)
	}
}

func TestEnsureDevCodeServerSkipsWhenNotRequested(t *testing.T) {
	restoreCodeServerTestHooks(t)

	called := false
	codeServerInstalled = func() bool {
		called = true
		return false
	}

	if err := ensureDevCodeServer(&state.Config{ContainerType: "dev", Runtime: "node"}); err != nil {
		t.Fatalf("ensureDevCodeServer: %v", err)
	}
	if called {
		t.Fatalf("code-server hooks were called for config without code-server request")
	}
}

func restoreCodeServerTestHooks(t *testing.T) {
	t.Helper()

	oldInstall := codeServerInstall
	oldStart := codeServerStart
	oldVerify := codeServerVerify
	oldInstalled := codeServerInstalled
	oldRunning := codeServerRunning

	t.Cleanup(func() {
		codeServerInstall = oldInstall
		codeServerStart = oldStart
		codeServerVerify = oldVerify
		codeServerInstalled = oldInstalled
		codeServerRunning = oldRunning
	})
}
