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"
)

// RapidAPISource searches public RapidAPI listings for exposed API keys.
// API listings often include code snippets and example requests where
// developers may accidentally paste real credentials. Credentialless.
type RapidAPISource struct {
	BaseURL  string
	Registry *providers.Registry
	Limiters *recon.LimiterRegistry
	Client   *Client
}

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

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

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

	queries := BuildQueries(s.Registry, "rapidapi")
	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
			}
		}

		// Search RapidAPI public listings. The search page renders HTML with
		// code examples and descriptions that may contain leaked keys.
		searchURL := fmt.Sprintf(
			"%s/search/%s?sortBy=ByRelevance&page=1",
			base, url.PathEscape(q),
		)

		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
		}

		if ciLogKeyPattern.Match(data) {
			out <- recon.Finding{
				ProviderName: q,
				Source:       fmt.Sprintf("https://rapidapi.com/search/%s", url.PathEscape(q)),
				SourceType:   "recon:rapidapi",
				Confidence:   "low",
				DetectedAt:   time.Now(),
			}
		}
	}
	return nil
}
