package pool

import (
	"strings"
	"testing"
)

func TestEnsurePoolValidation(t *testing.T) {
	m := NewManager(nil, nil)

	if _, err := m.EnsurePool(nil); err == nil {
		t.Fatal("nil config should error")
	}
	if _, err := m.EnsurePool(&Config{}); err == nil || !strings.Contains(err.Error(), "host") {
		t.Fatalf("empty host: %v", err)
	}
	if _, err := m.EnsurePool(&Config{Host: "pool.example.com"}); err == nil || !strings.Contains(err.Error(), "wallet") {
		t.Fatalf("empty wallet: %v", err)
	}
}

func TestGetPoolNilAndDefaults(t *testing.T) {
	m := NewManager(nil, nil)
	if p := m.GetPool(nil); p != nil {
		t.Fatal("nil config should return nil proxy")
	}
	if p := m.GetPool(&Config{}); p != nil {
		t.Fatal("incomplete config should return nil")
	}
}

func TestPoolKeyDistinct(t *testing.T) {
	a := poolKey(&Config{Host: "a.com", Port: 3333, UseTLS: false, Wallet: "w1"})
	b := poolKey(&Config{Host: "a.com", Port: 3333, UseTLS: true, Wallet: "w1"})
	if a == b {
		t.Fatal("TLS flag should affect pool key")
	}
}

func TestTruncateWallet(t *testing.T) {
	if truncateWallet("short", 12) != "short" {
		t.Fatal("short wallet unchanged")
	}
	if truncateWallet("012345678901234567890", 12) != "012345678901" {
		t.Fatalf("truncate wrong: %q", truncateWallet("012345678901234567890", 12))
	}
}

func TestPoolStatusLevel(t *testing.T) {
	if poolStatusLevel(false, false) != "red" {
		t.Fatal("disconnected = red")
	}
	if poolStatusLevel(true, false) != "yellow" {
		t.Fatal("connected no job = yellow")
	}
	if poolStatusLevel(true, true) != "green" {
		t.Fatal("connected with job = green")
	}
}

func TestManagerSetReconnectDelayAndVerbose(t *testing.T) {
	m := NewManager(nil, nil)
	m.SetReconnectDelay(0)
	m.SetReconnectDelay(30)
	m.SetVerboseTraffic(true)
	m.SetVerboseTraffic(false)
	if st := m.ListStatus(); len(st) != 0 {
		t.Fatalf("expected empty status, got %d", len(st))
	}
}

func TestPoolStatusJSONTags(t *testing.T) {
	st := PoolStatus{Key: "k", Host: "h", Port: 3333, UseTLS: true, Wallet: "w", Connected: true, Status: "green"}
	if st.Key == "" || st.Status != "green" {
		t.Fatalf("unexpected status struct: %+v", st)
	}
}
