package sources

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

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

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

const deployPreviewFixtureHTML = `<!DOCTYPE html>
<html>
<head><title>My App</title></head>
<body>
<div id="__next"></div>
<script id="__NEXT_DATA__" type="application/json">
{
  "props": {
    "pageProps": {
      "config": {
        "NEXT_PUBLIC_API_KEY": "sk-proj-abc123def456ghi789jkl"
      }
    }
  }
}
</script>
</body>
</html>`

const deployPreviewCleanHTML = `<!DOCTYPE html>
<html>
<head><title>My App</title></head>
<body>
<div id="root">Hello World</div>
</body>
</html>`

func TestDeployPreview_Sweep_ExtractsFindings(t *testing.T) {
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "text/html")
		_, _ = w.Write([]byte(deployPreviewFixtureHTML))
	}))
	defer srv.Close()

	src := &DeployPreviewSource{
		BaseURL:  srv.URL,
		Registry: deployPreviewTestRegistry(),
		Client:   NewClient(),
	}

	out := make(chan recon.Finding, 64)
	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) == 0 {
		t.Fatal("expected at least one finding")
	}
	for _, f := range findings {
		if f.SourceType != "recon:deploypreview" {
			t.Errorf("unexpected SourceType: %s", f.SourceType)
		}
		if f.Confidence != "medium" {
			t.Errorf("unexpected Confidence: %s", f.Confidence)
		}
	}
}

func TestDeployPreview_Sweep_NoFindings_OnCleanPage(t *testing.T) {
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "text/html")
		_, _ = w.Write([]byte(deployPreviewCleanHTML))
	}))
	defer srv.Close()

	src := &DeployPreviewSource{
		BaseURL:  srv.URL,
		Registry: deployPreviewTestRegistry(),
		Client:   NewClient(),
	}

	out := make(chan recon.Finding, 64)
	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 count int
	for range out {
		count++
	}
	if count != 0 {
		t.Errorf("expected 0 findings, got %d", count)
	}
}

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

	src := &DeployPreviewSource{
		BaseURL:  srv.URL,
		Registry: deployPreviewTestRegistry(),
		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")
	}
}

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

func TestDeployPreview_NameAndRate(t *testing.T) {
	s := &DeployPreviewSource{}
	if s.Name() != "deploypreview" {
		t.Errorf("unexpected name: %s", s.Name())
	}
	if s.Burst() != 2 {
		t.Errorf("burst: %d", s.Burst())
	}
	if !s.RespectsRobots() {
		t.Error("expected RespectsRobots=true")
	}
}
