package sources

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

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

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

const npmFixtureJSON = `{
  "objects": [
    {
      "package": {
        "name": "openai-key-checker",
        "links": {"npm": "https://www.npmjs.com/package/openai-key-checker"}
      }
    },
    {
      "package": {
        "name": "sk-proj-util",
        "links": {"npm": ""}
      }
    }
  ]
}`

func newNpmTestSource(srvURL string) *NpmSource {
	return &NpmSource{
		BaseURL:  srvURL,
		Registry: npmTestRegistry(),
		Limiters: recon.NewLimiterRegistry(),
		Client:   NewClient(),
	}
}

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

	src := newNpmTestSource(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:npm" {
			t.Errorf("unexpected SourceType: %s", f.SourceType)
		}
		if f.Confidence != "low" {
			t.Errorf("unexpected Confidence: %s", f.Confidence)
		}
	}
	if !got["https://www.npmjs.com/package/openai-key-checker"] {
		t.Error("missing finding with npm link")
	}
	// Second package has empty links.npm — should get constructed URL.
	if !got["https://www.npmjs.com/package/sk-proj-util"] {
		t.Error("missing finding with constructed URL")
	}
	if hits == 0 {
		t.Fatal("server was never hit")
	}
}

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

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

	src := newNpmTestSource(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 TestNpm_NameAndRate(t *testing.T) {
	s := &NpmSource{}
	if s.Name() != "npm" {
		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)
	}
}
