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

// NpmSource searches the npm registry for packages matching provider keywords.
// No credentials required. Emits findings tagged SourceType=recon:npm.
type NpmSource struct {
	BaseURL  string
	Registry *providers.Registry
	Limiters *recon.LimiterRegistry
	Client   *Client
}

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

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

// npm search JSON response structs.
type npmSearchResponse struct {
	Objects []npmObject `json:"objects"`
}

type npmObject struct {
	Package npmPackage `json:"package"`
}

type npmPackage struct {
	Name  string   `json:"name"`
	Links npmLinks `json:"links"`
}

type npmLinks struct {
	Npm string `json:"npm"`
}

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

	queries := BuildQueries(s.Registry, "npm")
	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/-/v1/search?text=%s&size=20", base, url.QueryEscape(q))
		req, err := http.NewRequestWithContext(ctx, http.MethodGet, searchURL, nil)
		if err != nil {
			return fmt.Errorf("npm: build req: %w", err)
		}

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

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

		for _, obj := range result.Objects {
			if err := ctx.Err(); err != nil {
				return err
			}
			source := obj.Package.Links.Npm
			if source == "" {
				source = fmt.Sprintf("https://www.npmjs.com/package/%s", obj.Package.Name)
			}
			out <- recon.Finding{
				ProviderName: "",
				Source:       source,
				SourceType:   "recon:npm",
				Confidence:   "low",
				DetectedAt:   time.Now(),
			}
		}
	}
	return nil
}
