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

// CratesIOSource searches crates.io for crates matching provider keywords.
// No credentials required. Emits findings tagged SourceType=recon:crates.
//
// crates.io requires a custom User-Agent header on all requests.
type CratesIOSource struct {
	BaseURL  string
	Registry *providers.Registry
	Limiters *recon.LimiterRegistry
	Client   *Client
}

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

// crates.io search JSON response structs.
type cratesSearchResponse struct {
	Crates []crateEntry `json:"crates"`
}

type crateEntry struct {
	ID         string `json:"id"`
	Name       string `json:"name"`
	Repository string `json:"repository"`
}

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

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

	queries := BuildQueries(s.Registry, "crates")
	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/crates?q=%s&per_page=20", base, url.QueryEscape(q))
		req, err := http.NewRequestWithContext(ctx, http.MethodGet, searchURL, nil)
		if err != nil {
			return fmt.Errorf("crates: build req: %w", err)
		}
		// crates.io requires a descriptive User-Agent header.
		req.Header.Set("User-Agent", "keyhunter-recon/1.0 (https://github.com/salvacybersec/keyhunter)")

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

		var result cratesSearchResponse
		if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
			_ = resp.Body.Close()
			return fmt.Errorf("crates: decode json: %w", err)
		}
		_ = resp.Body.Close()

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