package license

import (
	"context"
	"net/http"
	"net/http/httptest"
	"testing"
)

func TestHTTPConnectivityProberAllReachable(t *testing.T) {
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(http.StatusOK)
	}))
	defer srv.Close()
	p := NewHTTPConnectivityProber(srv.URL, srv.URL, srv.URL)
	if got := p.Probe(context.Background()); got != ProbeResultSelectiveBlock {
		t.Fatalf("all reachable: got %v, want ProbeResultSelectiveBlock", got)
	}
}

func TestHTTPConnectivityProberNoneReachable(t *testing.T) {
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}))
	srv.Close() // immediately close so all requests fail
	p := NewHTTPConnectivityProber(srv.URL, srv.URL, srv.URL)
	if got := p.Probe(context.Background()); got != ProbeResultNetworkDown {
		t.Fatalf("none reachable: got %v, want ProbeResultNetworkDown", got)
	}
}

func TestHTTPConnectivityProberOneReachable(t *testing.T) {
	ok := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(http.StatusOK)
	}))
	defer ok.Close()
	bad := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}))
	bad.Close()
	p := NewHTTPConnectivityProber(ok.URL, bad.URL, bad.URL)
	if got := p.Probe(context.Background()); got != ProbeResultUnknown {
		t.Fatalf("1/3 reachable: got %v, want ProbeResultUnknown", got)
	}
}

func TestHTTPConnectivityProberTwoReachable(t *testing.T) {
	ok := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(http.StatusOK)
	}))
	defer ok.Close()
	bad := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}))
	bad.Close()
	p := NewHTTPConnectivityProber(ok.URL, ok.URL, bad.URL)
	if got := p.Probe(context.Background()); got != ProbeResultSelectiveBlock {
		t.Fatalf("2/3 reachable: got %v, want ProbeResultSelectiveBlock", got)
	}
}

func TestHTTPConnectivityProberDefault(t *testing.T) {
	p := NewHTTPConnectivityProber()
	if len(p.endpoints) != 3 {
		t.Fatalf("default endpoints = %d, want 3", len(p.endpoints))
	}
}
