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

// PackagistSource searches Packagist (the PHP package registry) for packages
// matching provider keywords. The Packagist search API is public JSON and
// requires no authentication.
type PackagistSource struct {
	BaseURL  string
	Registry *providers.Registry
	Limiters *recon.LimiterRegistry
	Client   *Client
}

// Compile-time assertion that PackagistSource satisfies recon.ReconSource.
var _ recon.ReconSource = (*PackagistSource)(nil)

func (s *PackagistSource) Name() string          { return "packagist" }
func (s *PackagistSource) RateLimit() rate.Limit { return rate.Every(2 * time.Second) }
func (s *PackagistSource) Burst() int            { return 2 }
func (s *PackagistSource) RespectsRobots() bool  { return false }

// Enabled always returns true: Packagist search requires no credentials.
func (s *PackagistSource) Enabled(_ recon.Config) bool { return true }

// Sweep queries Packagist's search API for each provider keyword and emits a
// Finding per matching package.
func (s *PackagistSource) Sweep(ctx context.Context, _ string, out chan<- recon.Finding) error {
	base := s.BaseURL
	if base == "" {
		base = "https://packagist.org"
	}
	client := s.Client
	if client == nil {
		client = NewClient()
	}

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

		endpoint := fmt.Sprintf("%s/search.json?q=%s&per_page=20",
			base, url.QueryEscape(q))
		req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil)
		if err != nil {
			return fmt.Errorf("packagist: build request: %w", err)
		}
		req.Header.Set("Accept", "application/json")

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

		var parsed packagistSearchResponse
		decErr := json.NewDecoder(resp.Body).Decode(&parsed)
		_ = resp.Body.Close()
		if decErr != nil {
			continue
		}

		for _, pkg := range parsed.Results {
			if err := ctx.Err(); err != nil {
				return err
			}
			select {
			case out <- recon.Finding{
				Source:     pkg.URL,
				SourceType: "recon:packagist",
				Confidence: "low",
				DetectedAt: time.Now(),
			}:
			case <-ctx.Done():
				return ctx.Err()
			}
		}
	}
	return nil
}

type packagistSearchResponse struct {
	Results []packagistPackage `json:"results"`
}

type packagistPackage struct {
	Name string `json:"name"`
	URL  string `json:"url"`
}
