package sources

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

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

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

const swaggerFixtureJSON = `{
  "openapi": "3.0.0",
  "info": {"title": "My API", "version": "1.0"},
  "paths": {
    "/api/data": {
      "get": {
        "parameters": [
          {
            "name": "X-API-Key",
            "in": "header",
            "schema": {"type": "string"},
            "example": "sk-proj-abc123def456ghi789jkl"
          }
        ]
      }
    }
  },
  "components": {
    "securitySchemes": {
      "apiKey": {
        "type": "apiKey",
        "in": "header",
        "name": "Authorization",
        "default": "Bearer sk-live-xxxxxxxxxxxxxxxxxxxx"
      }
    }
  }
}`

const swaggerCleanFixtureJSON = `{
  "openapi": "3.0.0",
  "info": {"title": "My API", "version": "1.0"},
  "paths": {
    "/api/data": {
      "get": {
        "parameters": [
          {
            "name": "limit",
            "in": "query",
            "schema": {"type": "integer"},
            "example": 10
          }
        ]
      }
    }
  }
}`

func TestSwagger_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(swaggerFixtureJSON))
	}))
	defer srv.Close()

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

func TestSwagger_Sweep_NoFindings_OnCleanDoc(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(swaggerCleanFixtureJSON))
	}))
	defer srv.Close()

	src := &SwaggerSource{
		BaseURL:  srv.URL,
		Registry: swaggerTestRegistry(),
		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 TestSwagger_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(swaggerFixtureJSON))
	}))
	defer srv.Close()

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

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