package sources

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

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

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

const goProxyFixtureHTML = `<!doctype html>
<html><body>
  <a href="/github.com/example/openai-go">openai-go</a>
  <a href="/github.com/test/llm-client">llm-client</a>
  <a href="/about">about page</a>
  <a href="https://external.example.com">external</a>
  <a href="/search?q=next">pagination</a>
</body></html>`

func newGoProxyTestSource(srvURL string) *GoProxySource {
	return &GoProxySource{
		BaseURL:  srvURL,
		Registry: goProxyTestRegistry(),
		Limiters: recon.NewLimiterRegistry(),
		Client:   NewClient(),
	}
}

func TestGoProxy_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" {
			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", "text/html")
		_, _ = w.Write([]byte(goProxyFixtureHTML))
	}))
	defer srv.Close()

	src := newGoProxyTestSource(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)
	}
	// Should match the two Go module paths, not /about, /search, or external links
	if len(findings) != 2 {
		t.Fatalf("expected 2 findings, got %d", len(findings))
	}

	want1 := srv.URL + "/github.com/example/openai-go"
	want2 := srv.URL + "/github.com/test/llm-client"
	got := map[string]bool{}
	for _, f := range findings {
		got[f.Source] = true
		if f.SourceType != "recon:goproxy" {
			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 TestGoProxy_NameAndRate(t *testing.T) {
	s := &GoProxySource{}
	if s.Name() != "goproxy" {
		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 TestGoProxy_EnabledAlwaysTrue(t *testing.T) {
	s := &GoProxySource{}
	if !s.Enabled(recon.Config{}) {
		t.Fatal("expected Enabled=true")
	}
}

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

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