package proxypool

import (
	"testing"
	"time"
)

func TestNewWithProxiesDoesNotPanic(t *testing.T) {
	p := New([]string{
		"http://user:pass@proxy1.example:80",
		"http://proxy2.example:8080",
	})
	if p.Size() != 2 {
		t.Fatalf("want 2 entries, got %d", p.Size())
	}
	e := p.Next()
	if e == nil {
		t.Fatal("Next() must return an entry when proxies exist")
	}
}

func TestNewEmptyReturnsNil(t *testing.T) {
	p := New(nil)
	if p.Size() != 0 {
		t.Fatalf("want 0 entries, got %d", p.Size())
	}
	if p.Next() != nil {
		t.Fatal("Next() must be nil without proxies")
	}
}

func TestCooldownAfterFailures(t *testing.T) {
	p := New([]string{"http://p1:80", "http://p2:80"})
	e := p.entries[0]
	for i := 0; i < 3; i++ {
		e.ReportFailure(50 * time.Millisecond)
	}
	// While cooling down, Next must skip entry 0 and hand out entry 1.
	for i := 0; i < 4; i++ {
		got := p.Next()
		if got == e {
			t.Fatalf("cooling entry must be skipped, got it on iteration %d", i)
		}
	}
	time.Sleep(60 * time.Millisecond)
	found := false
	for i := 0; i < 4; i++ {
		if p.Next() == e {
			found = true
			break
		}
	}
	if !found {
		t.Fatal("entry must be available again after cooldown")
	}
}
