package sources

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

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

func TestGoogleDocs_Name(t *testing.T) {
	s := &GoogleDocsSource{}
	if s.Name() != "googledocs" {
		t.Fatalf("expected googledocs, got %s", s.Name())
	}
}

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

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

	// Mock search endpoint returning a doc URL.
	mux.HandleFunc("/search", func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json")
		_, _ = w.Write([]byte(`{"results":[{"url":"` + "http://" + r.Host + `/doc/d/1a2b3c","title":"Setup Guide"}]}`))
	})

	// Mock plain-text export with a leaked key.
	mux.HandleFunc("/doc/d/1a2b3c/export", func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "text/plain")
		_, _ = w.Write([]byte(`Setup Instructions
Step 1: Set your API key
auth_token = sk-proj-ABCDEF1234567890abcdef
Step 2: Run the service`))
	})

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

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

	s := &GoogleDocsSource{
		BaseURL:  srv.URL,
		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 Google Docs export")
	}
	if findings[0].SourceType != "recon:googledocs" {
		t.Fatalf("expected recon:googledocs, got %s", findings[0].SourceType)
	}
}
