package deploy

import (
	"encoding/json"
	"strings"
	"testing"
)

func TestStartCloudflaredTunnelEmptyURL(t *testing.T) {
	_, err := StartCloudflaredTunnel("")
	if err == nil || !strings.Contains(err.Error(), "server URL required") {
		t.Fatalf("expected URL error, got %v", err)
	}
	_, err = StartCloudflaredTunnel("   ")
	if err == nil {
		t.Fatal("whitespace-only URL should fail")
	}
}

func TestTunnelManagerRegisterAndStatus(t *testing.T) {
	ResetTrackedTunnels()
	oldAlive := processAliveFn
	processAliveFn = func(int) bool { return true }
	defer func() { processAliveFn = oldAlive }()

	RegisterTunnelPID(TunnelCloudflared, 4242, "https://example.com")
	RegisterTunnelPID(TunnelSSHForward, 9999, `{"local_port":2222,"remote_host":"10.0.0.5","remote_port":22}`)

	raw := TunnelStatus()
	var st TunnelStatusJSON
	if err := json.Unmarshal([]byte(raw), &st); err != nil {
		t.Fatalf("status json: %v", err)
	}
	if !st.CloudflaredRunning || st.CloudflaredPID != 4242 || st.CloudflaredURL != "https://example.com" {
		t.Fatalf("cloudflared status wrong: %+v", st)
	}
	if len(st.SSHForwards) != 1 || st.SSHForwards[0].LocalPort != 2222 {
		t.Fatalf("ssh forward status wrong: %+v", st.SSHForwards)
	}
}

func TestStopTunnelsEmptyRegistry(t *testing.T) {
	ResetTrackedTunnels()
	n, msgs := StopTunnels()
	if n != 0 {
		t.Fatalf("expected 0 stopped, got %d", n)
	}
	if len(msgs) != 0 {
		t.Fatalf("expected no msgs, got %v", msgs)
	}
}

func TestStartSSHForwardValidation(t *testing.T) {
	_, err := StartSSHForward(SSHForwardMeta{})
	if err == nil || !strings.Contains(err.Error(), "local_port") {
		t.Fatalf("expected local_port error, got %v", err)
	}
	_, err = StartSSHForward(SSHForwardMeta{LocalPort: 2222})
	if err == nil || !strings.Contains(err.Error(), "remote_host") {
		t.Fatalf("expected remote_host error, got %v", err)
	}
}
