package sources

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

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

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

const sourceMapFixtureJSON = `{
  "version": 3,
  "sources": ["src/api/client.ts"],
  "sourcesContent": ["const apiKey = \"sk-proj-abc123def456ghi789\";\nfetch('/api', {headers: {'Authorization': apiKey}});"]
}`

const sourceMapEmptyFixtureJSON = `{
  "version": 3,
  "sources": ["src/index.ts"],
  "sourcesContent": ["console.log('hello world');"]
}`

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

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

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

	src := &SourceMapSource{
		BaseURL:  srv.URL,
		Registry: sourceMapTestRegistry(),
		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 TestSourceMap_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(sourceMapFixtureJSON))
	}))
	defer srv.Close()

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

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