package sources

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

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

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

const nugetFixtureJSON = `{
  "data": [
    {"id": "OpenAI.SDK", "version": "2.1.0", "projectUrl": "https://github.com/example/openai-sdk"},
    {"id": "LLM.Client", "version": "1.0.0", "projectUrl": ""}
  ]
}`

func newNuGetTestSource(srvURL string) *NuGetSource {
	return &NuGetSource{
		BaseURL:  srvURL,
		Registry: nugetTestRegistry(),
		Limiters: recon.NewLimiterRegistry(),
		Client:   NewClient(),
	}
}

func TestNuGet_Sweep_ExtractsFindings(t *testing.T) {
	var hits int
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if r.URL.Path != "/query" {
			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(nugetFixtureJSON))
	}))
	defer srv.Close()

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

	// First package has projectUrl set
	if findings[0].Source != "https://github.com/example/openai-sdk" {
		t.Errorf("expected projectUrl for first finding, got: %s", findings[0].Source)
	}
	// Second package has empty projectUrl -> fallback
	if findings[1].Source != "https://www.nuget.org/packages/LLM.Client" {
		t.Errorf("expected nuget.org fallback for second finding, got: %s", findings[1].Source)
	}
	for _, f := range findings {
		if f.SourceType != "recon:nuget" {
			t.Errorf("unexpected SourceType: %s", f.SourceType)
		}
	}
	if hits == 0 {
		t.Fatal("server was never hit")
	}
}

func TestNuGet_NameAndRate(t *testing.T) {
	s := &NuGetSource{}
	if s.Name() != "nuget" {
		t.Errorf("unexpected name: %s", s.Name())
	}
	if s.Burst() != 3 {
		t.Errorf("burst: %d", s.Burst())
	}
	if s.RespectsRobots() {
		t.Error("expected RespectsRobots=false")
	}
}

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

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

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