package sources

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

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

func TestSwaggerHub_Name(t *testing.T) {
	s := &SwaggerHubSource{}
	if s.Name() != "swaggerhub" {
		t.Fatalf("expected swaggerhub, got %s", s.Name())
	}
}

func TestSwaggerHub_Enabled(t *testing.T) {
	s := &SwaggerHubSource{}
	if !s.Enabled(recon.Config{}) {
		t.Fatal("SwaggerHubSource should always be enabled")
	}
}

func TestSwaggerHub_Sweep(t *testing.T) {
	mux := http.NewServeMux()

	// Search endpoint returns one API with a spec URL.
	mux.HandleFunc("/specs", func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json")
		_, _ = w.Write([]byte(`{
			"apis": [
				{
					"name": "Payment Gateway",
					"url": "",
					"properties": [
						{"type": "Swagger", "url": "SPEC_URL_PLACEHOLDER"}
					]
				}
			]
		}`))
	})

	// Spec endpoint returns OpenAPI JSON with an embedded key.
	mux.HandleFunc("/spec/payment-gateway", func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json")
		_, _ = w.Write([]byte(`{
			"openapi": "3.0.0",
			"info": {"title": "Payment API"},
			"paths": {
				"/charge": {
					"post": {
						"parameters": [
							{
								"name": "Authorization",
								"in": "header",
								"example": "api_key = 'sk-proj-ABCDEF1234567890abcdef'"
							}
						]
					}
				}
			}
		}`))
	})

	srv := httptest.NewServer(mux)
	defer srv.Close()

	// Patch the spec URL placeholder with the test server URL.
	origHandler := mux
	_ = origHandler // keep for reference

	// Re-create with the actual server URL known.
	mux2 := http.NewServeMux()
	mux2.HandleFunc("/specs", func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json")
		_, _ = w.Write([]byte(`{
			"apis": [
				{
					"name": "Payment Gateway",
					"url": "` + srv.URL + `/spec/payment-gateway",
					"properties": []
				}
			]
		}`))
	})
	mux2.HandleFunc("/spec/payment-gateway", func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json")
		_, _ = w.Write([]byte(`{
			"openapi": "3.0.0",
			"paths": {
				"/charge": {
					"post": {
						"parameters": [
							{
								"name": "Authorization",
								"in": "header",
								"example": "api_key = 'sk-proj-ABCDEF1234567890abcdef'"
							}
						]
					}
				}
			}
		}`))
	})

	// Replace the handler on the existing server.
	srv.Config.Handler = mux2

	reg := providers.NewRegistryFromProviders([]providers.Provider{
		{Name: "openai", Keywords: []string{"sk-proj-"}},
	})

	s := &SwaggerHubSource{
		BaseURL:  srv.URL + "/specs",
		Registry: reg,
		Client:   NewClient(),
	}

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

	err := s.Sweep(ctx, "", 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 SwaggerHub")
	}
	if findings[0].SourceType != "recon:swaggerhub" {
		t.Fatalf("expected recon:swaggerhub, got %s", findings[0].SourceType)
	}
}

func TestSwaggerHub_Sweep_NoAPIs(t *testing.T) {
	mux := http.NewServeMux()
	mux.HandleFunc("/specs", func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json")
		_, _ = w.Write([]byte(`{"apis": []}`))
	})

	srv := httptest.NewServer(mux)
	defer srv.Close()

	reg := providers.NewRegistryFromProviders([]providers.Provider{
		{Name: "openai", Keywords: []string{"sk-proj-"}},
	})

	s := &SwaggerHubSource{
		BaseURL:  srv.URL + "/specs",
		Registry: reg,
		Client:   NewClient(),
	}

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

	err := s.Sweep(ctx, "", 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))
	}
}
