package sources

import (
	"context"
	"fmt"
	"io"
	"net/http"
	"regexp"
	"time"

	"golang.org/x/time/rate"

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

// JSBundleSource analyzes public JavaScript bundles for embedded API keys.
// Modern build tools (Webpack, Vite, esbuild, Rollup) inline environment
// variables and configuration at build time. This source probes common bundle
// paths and scans the minified JS for API key patterns, complementing
// WebpackSource by targeting raw key literals rather than env var prefixes.
type JSBundleSource struct {
	BaseURL  string
	Registry *providers.Registry
	Limiters *recon.LimiterRegistry
	Client   *Client
}

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

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

// jsBundleKeyPattern matches literal API key assignments commonly found in
// minified JS bundles (e.g., apiKey:"sk-proj-...", "Authorization":"Bearer sk-...").
var jsBundleKeyPattern = regexp.MustCompile(`(?i)(?:api[_-]?key|secret|token|authorization|bearer)\s*[=:"']+\s*['"]?([a-zA-Z0-9_\-]{20,})['"]?`)

// jsBundlePaths are common locations for production JS bundles.
var jsBundlePaths = []string{
	"/static/js/main.js",
	"/static/js/app.js",
	"/static/js/vendor.js",
	"/dist/app.js",
	"/dist/main.js",
	"/assets/app.js",
	"/assets/index.js",
	"/js/app.js",
	"/_next/static/chunks/main.js",
	"/_next/static/chunks/pages/_app.js",
}

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

	queries := BuildQueries(s.Registry, "jsbundle")
	if len(queries) == 0 {
		return nil
	}

	for _, q := range queries {
		if err := ctx.Err(); err != nil {
			return err
		}

		for _, path := range jsBundlePaths {
			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
				}
			}

			probeURL := fmt.Sprintf("%s%s", base, path)
			req, err := http.NewRequestWithContext(ctx, http.MethodGet, probeURL, nil)
			if err != nil {
				continue
			}

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

			body, err := io.ReadAll(io.LimitReader(resp.Body, 1024*1024)) // 1MB max for JS bundles
			_ = resp.Body.Close()
			if err != nil {
				continue
			}

			if jsBundleKeyPattern.Match(body) {
				out <- recon.Finding{
					ProviderName: q,
					Source:       probeURL,
					SourceType:   "recon:jsbundle",
					Confidence:   "medium",
					DetectedAt:   time.Now(),
				}
				break // one finding per query is sufficient
			}
		}
	}
	return nil
}
