package sources

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

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

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

const replitFixtureHTML = `<!doctype html>
<html><body>
  <a href="/@alice/super-bot">hit one</a>
  <a href="/@bob/weather-api">hit two</a>
  <a href="/about">nope</a>
  <a href="https://external.example.com/nope">external</a>
  <a href="/@carol/x/nested">too deep nope</a>
</body></html>`

func newReplitTestSource(srvURL string) *ReplitSource {
	return &ReplitSource{
		BaseURL:  srvURL,
		Registry: replitTestRegistry(),
		Limiters: recon.NewLimiterRegistry(),
		Client:   NewClient(),
	}
}

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

	src := newReplitTestSource(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))
	}
	wantA := srv.URL + "/@alice/super-bot"
	wantB := srv.URL + "/@bob/weather-api"
	got := map[string]bool{}
	for _, f := range findings {
		got[f.Source] = true
		if f.SourceType != "recon:replit" {
			t.Errorf("unexpected SourceType: %s", f.SourceType)
		}
	}
	if !got[wantA] || !got[wantB] {
		t.Fatalf("missing expected sources; got=%v", got)
	}
	if hits == 0 {
		t.Fatalf("server was never hit")
	}
}

func TestReplit_RespectsRobots(t *testing.T) {
	s := &ReplitSource{}
	if !s.RespectsRobots() {
		t.Fatal("expected RespectsRobots=true")
	}
}

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

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

	src := newReplitTestSource(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 TestReplit_NameAndRate(t *testing.T) {
	s := &ReplitSource{}
	if s.Name() != "replit" {
		t.Errorf("unexpected name: %s", s.Name())
	}
	if s.Burst() != 1 {
		t.Errorf("burst: %d", s.Burst())
	}
	want := float64(1) / 6
	got := float64(s.RateLimit())
	if got < want-0.01 || got > want+0.01 {
		t.Errorf("rate limit=%v want~%v", got, want)
	}
}
