package alexatop

import (
	"testing"
)

func TestFetchAlexaTop1M(t *testing.T) {
	urls, err := FetchAlexaTop1M()
	if err != nil {
		t.Fatalf("Expected no error, got %v", err)
	}

	if len(urls) < 700_000 {
		t.Fatalf("Expected at least 700,000 URLs, got %d", len(urls))
	}
}

func TestRandomSite(t *testing.T) {
	site, err := RandomSite()
	if err != nil {
		t.Fatalf("Expected no error, got %v", err)
	}

	if site == "" {
		t.Fatalf("Expected a valid URL, got an empty string")
	}
}

func TestNthSite(t *testing.T) {
	urls, err := FetchAlexaTop1M()
	if err != nil {
		t.Fatalf("Expected no error, got %v", err)
	}

	site, err := NthSite(99)
	if err != nil {
		t.Fatalf("Expected no error, got %v", err)
	}

	if site != urls[99] {
		t.Fatalf("Expected %s, got %s", urls[99], site)
	}

	_, err = NthSite(len(urls))
	if err == nil {
		t.Fatalf("Expected error for out-of-range index, got none")
	}
}

func TestRandomSites(t *testing.T) {
	n := 5
	randomSites, err := RandomSites(n)
	if err != nil {
		t.Fatalf("Expected no error, got %v", err)
	}

	if len(randomSites) != n {
		t.Fatalf("Expected %d random sites, got %d", n, len(randomSites))
	}

	for _, site := range randomSites {
		if site == "" {
			t.Fatalf("Expected a valid URL, got an empty string")
		}
	}
}

func TestRandomSitesMoreThanAvailable(t *testing.T) {
	urls, err := FetchAlexaTop1M()
	if err != nil {
		t.Fatalf("Expected no error, got %v", err)
	}

	_, err = RandomSites(len(urls) + 1)
	if err == nil {
		t.Fatalf("Expected error for requesting more sites than available, got none")
	}
}
