package backendclient

import (
	"net/http"
	"testing"
	"time"
)

// TestBackendTransportPoolsConnections guards the fix for the gateway->backend
// connection churn. Every synchronous client call proxies to the single backend host,
// so the REST client must widen the idle-connection pool past the default per-host cap
// of 2 (http.DefaultMaxIdleConnsPerHost) — otherwise almost every request under load
// opens a fresh TCP connection that then lingers in TIME_WAIT, burning gateway CPU and
// exhausting ephemeral ports. Reverting to the default transport (`&http.Client{...}`
// with no Transport) would silently reintroduce that, so assert the pool is widened.
func TestBackendTransportPoolsConnections(t *testing.T) {
	c, err := New("http://backend.invalid", "localhost:9090", time.Second)
	if err != nil {
		t.Fatalf("New: %v", err)
	}
	defer func() { _ = c.Close() }()

	tr, ok := c.http.Transport.(*http.Transport)
	if !ok {
		t.Fatalf("REST transport = %T, want a *http.Transport with a widened idle pool", c.http.Transport)
	}
	if tr.MaxIdleConnsPerHost <= http.DefaultMaxIdleConnsPerHost {
		t.Errorf("MaxIdleConnsPerHost = %d, want > default %d (else per-call connection churn)",
			tr.MaxIdleConnsPerHost, http.DefaultMaxIdleConnsPerHost)
	}
}
