package sources

import (
	"context"
	"encoding/json"
	"fmt"
	"net/http"
	"net/url"
	"time"

	"golang.org/x/time/rate"

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

// RubyGemsSource searches rubygems.org for gems matching provider keywords.
// No credentials required. Emits findings tagged SourceType=recon:rubygems.
type RubyGemsSource struct {
	BaseURL  string
	Registry *providers.Registry
	Limiters *recon.LimiterRegistry
	Client   *Client
}

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

// rubyGemEntry represents one entry in the RubyGems search JSON array.
type rubyGemEntry struct {
	Name       string `json:"name"`
	ProjectURI string `json:"project_uri"`
}

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

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

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

		searchURL := fmt.Sprintf("%s/api/v1/search.json?query=%s&page=1", base, url.QueryEscape(q))
		req, err := http.NewRequestWithContext(ctx, http.MethodGet, searchURL, nil)
		if err != nil {
			return fmt.Errorf("rubygems: build req: %w", err)
		}

		resp, err := client.Do(ctx, req)
		if err != nil {
			return fmt.Errorf("rubygems: fetch: %w", err)
		}

		var gems []rubyGemEntry
		if err := json.NewDecoder(resp.Body).Decode(&gems); err != nil {
			_ = resp.Body.Close()
			return fmt.Errorf("rubygems: decode json: %w", err)
		}
		_ = resp.Body.Close()

		for _, g := range gems {
			if err := ctx.Err(); err != nil {
				return err
			}
			source := g.ProjectURI
			if source == "" {
				source = fmt.Sprintf("https://rubygems.org/gems/%s", g.Name)
			}
			out <- recon.Finding{
				ProviderName: "",
				Source:       source,
				SourceType:   "recon:rubygems",
				Confidence:   "low",
				DetectedAt:   time.Now(),
			}
		}
	}
	return nil
}
