package sources

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

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

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

const mavenFixtureJSON = `{
  "response": {
    "numFound": 2,
    "docs": [
      {"g": "com.example", "a": "openai-sdk", "latestVersion": "1.2.3"},
      {"g": "org.test", "a": "llm-client", "latestVersion": "0.9.0"}
    ]
  }
}`

func newMavenTestSource(srvURL string) *MavenSource {
	return &MavenSource{
		BaseURL:  srvURL,
		Registry: mavenTestRegistry(),
		Limiters: recon.NewLimiterRegistry(),
		Client:   NewClient(),
	}
}

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

	src := newMavenTestSource(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))
	}
	for _, f := range findings {
		if f.SourceType != "recon:maven" {
			t.Errorf("unexpected SourceType: %s", f.SourceType)
		}
	}
	if hits == 0 {
		t.Fatal("server was never hit")
	}
}

func TestMaven_NameAndRate(t *testing.T) {
	s := &MavenSource{}
	if s.Name() != "maven" {
		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")
	}
}

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

func TestMaven_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(mavenFixtureJSON))
	}))
	defer srv.Close()

	src := newMavenTestSource(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")
	}
}
