package sources

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

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

func gistPasteTestRegistry() *providers.Registry {
	return providers.NewRegistryFromProviders([]providers.Provider{
		{Name: "anthropic", Keywords: []string{"sk-ant-"}},
	})
}

const gistPasteSearchHTML = `<!doctype html>
<html><body>
  <a href="/alice/abc123def456">gist one</a>
  <a href="/bob/789aaa000bbb">gist two</a>
  <a href="/about">nope</a>
  <a href="/trending">nope</a>
</body></html>`

const gistPasteRaw1 = `config with sk-ant-XYZKEY123 inside`
const gistPasteRaw2 = `nothing here`

func TestGistPaste_Sweep_ExtractsFindings(t *testing.T) {
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		switch {
		case r.URL.Path == "/search":
			w.Header().Set("Content-Type", "text/html")
			_, _ = w.Write([]byte(gistPasteSearchHTML))
		case r.URL.Path == "/alice/abc123def456/raw":
			_, _ = w.Write([]byte(gistPasteRaw1))
		case r.URL.Path == "/bob/789aaa000bbb/raw":
			_, _ = w.Write([]byte(gistPasteRaw2))
		default:
			http.NotFound(w, r)
		}
	}))
	defer srv.Close()

	src := &GistPasteSource{
		BaseURL:  srv.URL,
		Registry: gistPasteTestRegistry(),
		Limiters: recon.NewLimiterRegistry(),
		Client:   NewClient(),
	}

	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) != 1 {
		t.Fatalf("expected 1 finding, got %d", len(findings))
	}
	f := findings[0]
	if f.SourceType != "recon:gistpaste" {
		t.Errorf("SourceType=%s, want recon:gistpaste", f.SourceType)
	}
	if f.ProviderName != "anthropic" {
		t.Errorf("ProviderName=%s, want anthropic", f.ProviderName)
	}
	wantSource := srv.URL + "/alice/abc123def456"
	if f.Source != wantSource {
		t.Errorf("Source=%s, want %s", f.Source, wantSource)
	}
}

func TestGistPaste_NameAndRate(t *testing.T) {
	s := &GistPasteSource{}
	if s.Name() != "gistpaste" {
		t.Errorf("Name=%s", s.Name())
	}
	if s.Burst() != 1 {
		t.Errorf("Burst=%d", s.Burst())
	}
	if !s.RespectsRobots() {
		t.Error("expected RespectsRobots=true")
	}
	if !s.Enabled(recon.Config{}) {
		t.Error("expected Enabled=true")
	}
}

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

	src := &GistPasteSource{
		BaseURL:  srv.URL,
		Registry: gistPasteTestRegistry(),
		Limiters: recon.NewLimiterRegistry(),
		Client:   NewClient(),
	}
	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")
	}
}
