package sources

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

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

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

const webpackFixtureJS = `
!function(e){var t={};function n(r){if(t[r])return t[r].exports}
var config = {
  NEXT_PUBLIC_API_KEY: "sk-proj-abc123def456ghi789jkl",
  REACT_APP_SECRET: "super-secret-value-12345678"
};
module.exports = config;
`

const webpackCleanJS = `
!function(e){var t={};function n(r){if(t[r])return t[r].exports}
console.log("clean bundle");
module.exports = {};
`

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

	src := &WebpackSource{
		BaseURL:  srv.URL,
		Registry: webpackTestRegistry(),
		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:webpack" {
			t.Errorf("unexpected SourceType: %s", f.SourceType)
		}
		if f.Confidence != "medium" {
			t.Errorf("unexpected Confidence: %s", f.Confidence)
		}
	}
}

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

	src := &WebpackSource{
		BaseURL:  srv.URL,
		Registry: webpackTestRegistry(),
		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 TestWebpack_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(webpackFixtureJS))
	}))
	defer srv.Close()

	src := &WebpackSource{
		BaseURL:  srv.URL,
		Registry: webpackTestRegistry(),
		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 TestWebpack_EnabledAlwaysTrue(t *testing.T) {
	s := &WebpackSource{}
	if !s.Enabled(recon.Config{}) {
		t.Fatal("expected Enabled=true")
	}
}

func TestWebpack_NameAndRate(t *testing.T) {
	s := &WebpackSource{}
	if s.Name() != "webpack" {
		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")
	}
}
