package sources

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

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

func TestSecurityTrails_Name(t *testing.T) {
	s := &SecurityTrailsSource{}
	if s.Name() != "securitytrails" {
		t.Fatalf("expected securitytrails, got %s", s.Name())
	}
}

func TestSecurityTrails_Enabled(t *testing.T) {
	s := &SecurityTrailsSource{}
	if s.Enabled(recon.Config{}) {
		t.Fatal("SecurityTrailsSource should be disabled without API key")
	}

	s.APIKey = "test-key"
	if !s.Enabled(recon.Config{}) {
		t.Fatal("SecurityTrailsSource should be enabled with API key")
	}
}

func TestSecurityTrails_Sweep(t *testing.T) {
	// API server mocks SecurityTrails endpoints.
	apiMux := http.NewServeMux()

	// Subdomain enumeration.
	apiMux.HandleFunc("/domain/example.com/subdomains", func(w http.ResponseWriter, r *http.Request) {
		if r.Header.Get("APIKEY") != "test-key" {
			http.Error(w, "unauthorized", http.StatusUnauthorized)
			return
		}
		w.Header().Set("Content-Type", "application/json")
		_, _ = w.Write([]byte(`{"subdomains":["api","staging"]}`))
	})

	// DNS history.
	apiMux.HandleFunc("/domain/example.com", func(w http.ResponseWriter, r *http.Request) {
		if r.Header.Get("APIKEY") != "test-key" {
			http.Error(w, "unauthorized", http.StatusUnauthorized)
			return
		}
		w.Header().Set("Content-Type", "application/json")
		_, _ = w.Write([]byte(`{"current_dns":{"txt":{"values":[{"value":"token = sk-proj-ABCDEF1234567890abcdef"}]}}}`))
	})

	apiSrv := httptest.NewServer(apiMux)
	defer apiSrv.Close()

	// Probe server.
	probeMux := http.NewServeMux()
	probeMux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		if strings.HasSuffix(r.URL.Path, "/.env") {
			_, _ = w.Write([]byte(`SECRET_KEY = "sk-proj-ABCDEF1234567890abcdef"`))
			return
		}
		http.NotFound(w, r)
	})
	probeSrv := httptest.NewServer(probeMux)
	defer probeSrv.Close()

	s := &SecurityTrailsSource{
		APIKey:       "test-key",
		BaseURL:      apiSrv.URL,
		Client:       NewClient(),
		ProbeBaseURL: probeSrv.URL,
	}

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

	err := s.Sweep(ctx, "example.com", out)
	close(out)
	if err != nil {
		t.Fatalf("Sweep error: %v", err)
	}

	var findings []recon.Finding
	for f := range out {
		findings = append(findings, f)
	}
	if len(findings) == 0 {
		t.Fatal("expected at least one finding from SecurityTrails")
	}

	// Check that we got both probe findings and DNS history findings.
	var probeFound, dnsFound bool
	for _, f := range findings {
		if f.SourceType != "recon:securitytrails" {
			t.Fatalf("expected recon:securitytrails, got %s", f.SourceType)
		}
		if strings.Contains(f.Source, "/.env") {
			probeFound = true
		}
		if strings.Contains(f.Source, "/domain/example.com") && !strings.Contains(f.Source, "subdomains") {
			dnsFound = true
		}
	}
	if !probeFound {
		t.Fatal("expected probe finding from SecurityTrails")
	}
	if !dnsFound {
		t.Fatal("expected DNS history finding from SecurityTrails")
	}
}

func TestSecurityTrails_Sweep_SkipsKeywords(t *testing.T) {
	s := &SecurityTrailsSource{
		APIKey: "test-key",
		Client: NewClient(),
	}

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

	err := s.Sweep(ctx, "sk-proj-", out)
	close(out)
	if err != nil {
		t.Fatalf("Sweep error: %v", err)
	}

	var findings []recon.Finding
	for f := range out {
		findings = append(findings, f)
	}
	if len(findings) != 0 {
		t.Fatalf("expected no findings for keyword query, got %d", len(findings))
	}
}

func TestSecurityTrails_Sweep_NoSubdomains(t *testing.T) {
	apiMux := http.NewServeMux()
	apiMux.HandleFunc("/domain/empty.example.com/subdomains", func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json")
		_, _ = w.Write([]byte(`{"subdomains":[]}`))
	})
	apiMux.HandleFunc("/domain/empty.example.com", func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json")
		_, _ = w.Write([]byte(`{"current_dns":{}}`))
	})

	apiSrv := httptest.NewServer(apiMux)
	defer apiSrv.Close()

	s := &SecurityTrailsSource{
		APIKey:  "test-key",
		BaseURL: apiSrv.URL,
		Client:  NewClient(),
	}

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

	err := s.Sweep(ctx, "empty.example.com", out)
	close(out)
	if err != nil {
		t.Fatalf("Sweep error: %v", err)
	}

	var findings []recon.Finding
	for f := range out {
		findings = append(findings, f)
	}
	if len(findings) != 0 {
		t.Fatalf("expected no findings, got %d", len(findings))
	}
}
