package sources

import (
	"context"
	"fmt"
	"io"
	"net/http"
	"net/url"
	"time"

	"golang.org/x/time/rate"

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

// PostmanSource searches public Postman collections and workspaces for
// hardcoded API keys. The Postman public network exposes a search proxy
// that does not require authentication.
type PostmanSource struct {
	BaseURL  string
	Registry *providers.Registry
	Limiters *recon.LimiterRegistry
	Client   *Client
}

var _ recon.ReconSource = (*PostmanSource)(nil)

func (s *PostmanSource) Name() string              { return "postman" }
func (s *PostmanSource) RateLimit() rate.Limit      { return rate.Every(3 * time.Second) }
func (s *PostmanSource) Burst() int                 { return 3 }
func (s *PostmanSource) RespectsRobots() bool       { return false }
func (s *PostmanSource) Enabled(_ recon.Config) bool { return true }

func (s *PostmanSource) Sweep(ctx context.Context, query string, out chan<- recon.Finding) error {
	base := s.BaseURL
	if base == "" {
		base = "https://www.postman.com/_api"
	}
	client := s.Client
	if client == nil {
		client = NewClient()
	}

	queries := BuildQueries(s.Registry, "postman")
	if len(queries) == 0 {
		return nil
	}

	for _, q := range queries {
		if err := ctx.Err(); err != nil {
			return err
		}

		if s.Limiters != nil {
			if err := s.Limiters.Wait(ctx, s.Name(), s.RateLimit(), s.Burst(), false); err != nil {
				return err
			}
		}

		// Use Postman's internal search proxy. The encoded request parameter
		// targets /search/all with the query text.
		searchPath := fmt.Sprintf("/search/all?querytext=%s&size=10&type=all",
			url.QueryEscape(q))
		searchURL := fmt.Sprintf("%s/ws/proxy?request=%s",
			base, url.QueryEscape(searchPath))

		req, err := http.NewRequestWithContext(ctx, http.MethodGet, searchURL, nil)
		if err != nil {
			continue
		}

		resp, err := client.Do(ctx, req)
		if err != nil {
			continue
		}

		data, err := io.ReadAll(io.LimitReader(resp.Body, 512*1024))
		_ = resp.Body.Close()
		if err != nil {
			continue
		}

		// Scan the raw response body for key patterns. Postman search results
		// include snippets of collection contents where keys may appear.
		content := string(data)
		if ciLogKeyPattern.MatchString(content) {
			out <- recon.Finding{
				ProviderName: q,
				Source:       fmt.Sprintf("https://www.postman.com/search?q=%s", url.QueryEscape(q)),
				SourceType:   "recon:postman",
				Confidence:   "medium",
				DetectedAt:   time.Now(),
			}
		}
	}
	return nil
}
