package sources

import (
	"context"
	"encoding/json"
	"errors"
	"net/http"
	"net/http/httptest"
	"sync/atomic"
	"testing"
	"time"

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

func terraformStubHandler(t *testing.T, calls *int32) http.HandlerFunc {
	t.Helper()
	return func(w http.ResponseWriter, r *http.Request) {
		atomic.AddInt32(calls, 1)
		if r.URL.Path != "/v1/modules" {
			t.Errorf("unexpected path: %s", r.URL.Path)
		}
		if r.URL.Query().Get("q") == "" {
			t.Errorf("missing q param")
		}
		body := terraformSearchResponse{
			Modules: []terraformModule{
				{
					ID:        "hashicorp/openai/aws",
					Namespace: "hashicorp",
					Name:      "openai",
					Provider:  "aws",
				},
				{
					ID:        "community/llm-gateway/azure",
					Namespace: "community",
					Name:      "llm-gateway",
					Provider:  "azure",
				},
			},
		}
		w.Header().Set("Content-Type", "application/json")
		_ = json.NewEncoder(w).Encode(body)
	}
}

func TestTerraform_SweepEmitsFindings(t *testing.T) {
	reg := syntheticRegistry()
	lim := recon.NewLimiterRegistry()
	_ = lim.For("terraform", 1000, 100)

	var calls int32
	srv := httptest.NewServer(terraformStubHandler(t, &calls))
	defer srv.Close()

	src := &TerraformSource{
		BaseURL:  srv.URL,
		Registry: reg,
		Limiters: lim,
		Client:   NewClient(),
	}

	out := make(chan recon.Finding, 32)
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()

	done := make(chan error, 1)
	go func() { done <- src.Sweep(ctx, "", out); close(out) }()

	var findings []recon.Finding
	for f := range out {
		findings = append(findings, f)
	}
	if err := <-done; err != nil {
		t.Fatalf("Sweep error: %v", err)
	}

	// 2 keywords * 2 modules = 4 findings
	if len(findings) != 4 {
		t.Fatalf("expected 4 findings, got %d", len(findings))
	}
	for _, f := range findings {
		if f.SourceType != "recon:terraform" {
			t.Errorf("SourceType=%q want recon:terraform", f.SourceType)
		}
	}
	if got := atomic.LoadInt32(&calls); got != 2 {
		t.Errorf("expected 2 server calls, got %d", got)
	}
}

func TestTerraform_ModuleURLConstruction(t *testing.T) {
	reg := syntheticRegistry()
	lim := recon.NewLimiterRegistry()
	_ = lim.For("terraform", 1000, 100)

	var calls int32
	srv := httptest.NewServer(terraformStubHandler(t, &calls))
	defer srv.Close()

	src := &TerraformSource{
		BaseURL:  srv.URL,
		Registry: reg,
		Limiters: lim,
		Client:   NewClient(),
	}

	out := make(chan recon.Finding, 32)
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()

	done := make(chan error, 1)
	go func() { done <- src.Sweep(ctx, "", out); close(out) }()

	var findings []recon.Finding
	for f := range out {
		findings = append(findings, f)
	}
	if err := <-done; err != nil {
		t.Fatalf("Sweep error: %v", err)
	}

	// Verify URL contains namespace/name/provider structure.
	hasHashicorp := false
	hasCommunity := false
	for _, f := range findings {
		if contains(f.Source, "/modules/hashicorp/openai/aws") {
			hasHashicorp = true
		}
		if contains(f.Source, "/modules/community/llm-gateway/azure") {
			hasCommunity = true
		}
	}
	if !hasHashicorp {
		t.Error("expected finding with hashicorp/openai/aws module URL")
	}
	if !hasCommunity {
		t.Error("expected finding with community/llm-gateway/azure module URL")
	}
}

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

func TestTerraform_NameAndRate(t *testing.T) {
	s := &TerraformSource{}
	if s.Name() != "terraform" {
		t.Errorf("unexpected name: %s", s.Name())
	}
	if s.Burst() != 2 {
		t.Errorf("burst: %d", s.Burst())
	}
	if s.RespectsRobots() {
		t.Error("expected RespectsRobots=false")
	}
}

func TestTerraform_CtxCancelled(t *testing.T) {
	reg := syntheticRegistry()
	lim := recon.NewLimiterRegistry()
	_ = lim.For("terraform", 1000, 100)

	src := &TerraformSource{
		BaseURL:  "http://127.0.0.1:1",
		Registry: reg,
		Limiters: lim,
		Client:   NewClient(),
	}

	ctx, cancel := context.WithCancel(context.Background())
	cancel()

	out := make(chan recon.Finding, 1)
	err := src.Sweep(ctx, "", out)
	if !errors.Is(err, context.Canceled) {
		t.Fatalf("expected context.Canceled, got %v", err)
	}
}

func TestTerraform_NilRegistryNoError(t *testing.T) {
	src := &TerraformSource{Client: NewClient()}
	out := make(chan recon.Finding, 1)
	if err := src.Sweep(context.Background(), "", out); err != nil {
		t.Fatalf("expected nil, got %v", err)
	}
}
