package sources

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

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

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

const codesandboxFixtureHTML = `<!doctype html>
<html><body>
  <a href="/s/abc123-def">one</a>
  <a href="/s/XYZ-789">two</a>
  <a href="/docs">skip</a>
  <a href="/s/abc/extra/path">skip deeper</a>
</body></html>`

func newCodeSandboxTestSource(srvURL string) *CodeSandboxSource {
	return &CodeSandboxSource{
		BaseURL:  srvURL,
		Registry: codesandboxTestRegistry(),
		Limiters: recon.NewLimiterRegistry(),
		Client:   NewClient(),
	}
}

func TestCodeSandbox_Sweep_ExtractsFindings(t *testing.T) {
	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("query") == "" {
			t.Errorf("missing query param")
		}
		w.Header().Set("Content-Type", "text/html")
		_, _ = w.Write([]byte(codesandboxFixtureHTML))
	}))
	defer srv.Close()

	src := newCodeSandboxTestSource(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))
	}
	for _, f := range findings {
		if f.SourceType != "recon:codesandbox" {
			t.Errorf("unexpected SourceType: %s", f.SourceType)
		}
	}
}

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

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

func TestCodeSandbox_Sweep_CtxCancelled(t *testing.T) {
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		time.Sleep(500 * time.Millisecond)
	}))
	defer srv.Close()

	src := newCodeSandboxTestSource(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 TestCodeSandbox_NameAndRate(t *testing.T) {
	s := &CodeSandboxSource{}
	if s.Name() != "codesandbox" {
		t.Fatalf("unexpected name: %s", s.Name())
	}
}
