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

// NuGetSource searches the NuGet gallery for .NET packages matching provider
// keywords. The NuGet search API is public and requires no authentication.
type NuGetSource struct {
	BaseURL  string
	Registry *providers.Registry
	Limiters *recon.LimiterRegistry
	Client   *Client
}

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

func (s *NuGetSource) Name() string          { return "nuget" }
func (s *NuGetSource) RateLimit() rate.Limit { return rate.Every(1 * time.Second) }
func (s *NuGetSource) Burst() int            { return 3 }
func (s *NuGetSource) RespectsRobots() bool  { return false }

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

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

	queries := BuildQueries(s.Registry, "nuget")
	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/query?q=%s&take=20",
			base, url.QueryEscape(q))
		req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil)
		if err != nil {
			return fmt.Errorf("nuget: build request: %w", err)
		}
		req.Header.Set("Accept", "application/json")

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

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

		for _, pkg := range parsed.Data {
			if err := ctx.Err(); err != nil {
				return err
			}
			src := pkg.ProjectURL
			if src == "" {
				src = fmt.Sprintf("https://www.nuget.org/packages/%s", pkg.ID)
			}
			select {
			case out <- recon.Finding{
				Source:     src,
				SourceType: "recon:nuget",
				Confidence: "low",
				DetectedAt: time.Now(),
			}:
			case <-ctx.Done():
				return ctx.Err()
			}
		}
	}
	return nil
}

type nugetSearchResponse struct {
	Data []nugetPackage `json:"data"`
}

type nugetPackage struct {
	ID         string `json:"id"`
	Version    string `json:"version"`
	ProjectURL string `json:"projectUrl"`
}
