package sources

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

	"github.com/salvacybersec/keyhunter/pkg/providers"
	"github.com/salvacybersec/keyhunter/pkg/recon"
)

func rubygemsTestRegistry() *providers.Registry {
	return providers.NewRegistryFromProviders([]providers.Provider{
		{Name: "openai", Keywords: []string{"sk-proj-"}},
	})
}

const rubygemsFixtureJSON = `[
  {"name": "openai-ruby", "project_uri": "https://rubygems.org/gems/openai-ruby"},
  {"name": "sk-proj-gem", "project_uri": ""}
]`

func newRubyGemsTestSource(srvURL string) *RubyGemsSource {
	return &RubyGemsSource{
		BaseURL:  srvURL,
		Registry: rubygemsTestRegistry(),
		Limiters: recon.NewLimiterRegistry(),
		Client:   NewClient(),
	}
}

func TestRubyGems_Sweep_ExtractsFindings(t *testing.T) {
	var hits int
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if r.URL.Path != "/api/v1/search.json" {
			t.Errorf("unexpected path: %s", r.URL.Path)
		}
		if r.URL.Query().Get("query") == "" {
			t.Errorf("missing query param")
		}
		hits++
		w.Header().Set("Content-Type", "application/json")
		_, _ = w.Write([]byte(rubygemsFixtureJSON))
	}))
	defer srv.Close()

	src := newRubyGemsTestSource(srv.URL)
	out := make(chan recon.Finding, 16)
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()

	if err := src.Sweep(ctx, "", out); err != nil {
		t.Fatalf("Sweep err: %v", err)
	}
	close(out)

	var findings []recon.Finding
	for f := range out {
		findings = append(findings, f)
	}
	if len(findings) != 2 {
		t.Fatalf("expected 2 findings, got %d", len(findings))
	}

	got := map[string]bool{}
	for _, f := range findings {
		got[f.Source] = true
		if f.SourceType != "recon:rubygems" {
			t.Errorf("unexpected SourceType: %s", f.SourceType)
		}
		if f.Confidence != "low" {
			t.Errorf("unexpected Confidence: %s", f.Confidence)
		}
	}
	if !got["https://rubygems.org/gems/openai-ruby"] {
		t.Error("missing openai-ruby finding")
	}
	// Second gem has empty project_uri — should get constructed URL.
	if !got["https://rubygems.org/gems/sk-proj-gem"] {
		t.Error("missing sk-proj-gem finding")
	}
	if hits == 0 {
		t.Fatal("server was never hit")
	}
}

func TestRubyGems_EnabledAlwaysTrue(t *testing.T) {
	s := &RubyGemsSource{}
	if !s.Enabled(recon.Config{}) {
		t.Fatal("expected Enabled=true")
	}
}

func TestRubyGems_Sweep_CtxCancelled(t *testing.T) {
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		time.Sleep(500 * time.Millisecond)
		_, _ = w.Write([]byte(rubygemsFixtureJSON))
	}))
	defer srv.Close()

	src := newRubyGemsTestSource(srv.URL)
	ctx, cancel := context.WithCancel(context.Background())
	cancel()

	out := make(chan recon.Finding, 4)
	if err := src.Sweep(ctx, "", out); err == nil {
		t.Fatal("expected ctx error")
	}
}

func TestRubyGems_NameAndRate(t *testing.T) {
	s := &RubyGemsSource{}
	if s.Name() != "rubygems" {
		t.Errorf("unexpected name: %s", s.Name())
	}
	if s.Burst() != 2 {
		t.Errorf("burst: %d", s.Burst())
	}
	if s.RespectsRobots() {
		t.Error("expected RespectsRobots=false")
	}
	want := float64(1) / 2
	got := float64(s.RateLimit())
	if got < want-0.01 || got > want+0.01 {
		t.Errorf("rate limit=%v want~%v", got, want)
	}
}
