package transport

import (
	"testing"
	"time"
)

func TestConnectOptionsDefaults(t *testing.T) {
	opts := ConnectOptions{
		Addr:               "127.0.0.1:5001",
		InsecureSkipVerify: true,
	}
	if opts.Addr != "127.0.0.1:5001" {
		t.Errorf("unexpected addr: %s", opts.Addr)
	}
	if !opts.InsecureSkipVerify {
		t.Error("expected InsecureSkipVerify=true")
	}
	if opts.ConnectTimeout != 0 {
		t.Errorf("expected zero timeout, got %v", opts.ConnectTimeout)
	}
}

func TestBuildTLSConfigInsecure(t *testing.T) {
	cfg, err := buildTLSConfig(ConnectOptions{InsecureSkipVerify: true})
	if err != nil {
		t.Fatalf("buildTLSConfig: %v", err)
	}
	if !cfg.InsecureSkipVerify {
		t.Error("expected InsecureSkipVerify=true in TLS config")
	}
	if len(cfg.NextProtos) != 1 || cfg.NextProtos[0] != "capnp" {
		t.Errorf("expected ALPN [capnp], got %v", cfg.NextProtos)
	}
	if cfg.MinVersion != 0x0304 { // tls.VersionTLS13
		t.Errorf("expected TLS 1.3 min version (0x0304), got 0x%04x", cfg.MinVersion)
	}
}

func TestBuildTLSConfigWithMissingCA(t *testing.T) {
	_, err := buildTLSConfig(ConnectOptions{CACertPath: "/nonexistent/ca.pem"})
	if err == nil {
		t.Error("expected error for missing CA cert")
	}
}

func TestBuildTLSConfigDefault(t *testing.T) {
	cfg, err := buildTLSConfig(ConnectOptions{})
	if err != nil {
		t.Fatalf("buildTLSConfig: %v", err)
	}
	if cfg.InsecureSkipVerify {
		t.Error("expected InsecureSkipVerify=false by default")
	}
	if cfg.NextProtos[0] != "capnp" {
		t.Error("expected ALPN capnp")
	}
}

func TestConnectTimeoutDefault(t *testing.T) {
	opts := ConnectOptions{Addr: "127.0.0.1:5001"}
	timeout := opts.ConnectTimeout
	if timeout == 0 {
		timeout = 10 * time.Second
	}
	if timeout != 10*time.Second {
		t.Errorf("expected 10s default timeout, got %v", timeout)
	}
}
