package sources

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

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

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

const packagistFixtureJSON = `{
  "results": [
    {"name": "vendor/openai-php", "url": "https://packagist.org/packages/vendor/openai-php"},
    {"name": "other/llm-sdk", "url": "https://packagist.org/packages/other/llm-sdk"}
  ]
}`

func newPackagistTestSource(srvURL string) *PackagistSource {
	return &PackagistSource{
		BaseURL:  srvURL,
		Registry: packagistTestRegistry(),
		Limiters: recon.NewLimiterRegistry(),
		Client:   NewClient(),
	}
}

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

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

	want1 := "https://packagist.org/packages/vendor/openai-php"
	want2 := "https://packagist.org/packages/other/llm-sdk"
	got := map[string]bool{}
	for _, f := range findings {
		got[f.Source] = true
		if f.SourceType != "recon:packagist" {
			t.Errorf("unexpected SourceType: %s", f.SourceType)
		}
	}
	if !got[want1] || !got[want2] {
		t.Fatalf("missing expected sources; got=%v", got)
	}
	if hits == 0 {
		t.Fatal("server was never hit")
	}
}

func TestPackagist_NameAndRate(t *testing.T) {
	s := &PackagistSource{}
	if s.Name() != "packagist" {
		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 TestPackagist_EnabledAlwaysTrue(t *testing.T) {
	s := &PackagistSource{}
	if !s.Enabled(recon.Config{}) {
		t.Fatal("expected Enabled=true")
	}
}

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

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