package sources

import (
	"context"
	"encoding/json"
	"net/http"
	"regexp"
	"time"

	"golang.org/x/time/rate"

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

// SourceMapSource probes for publicly accessible JavaScript source maps (.map
// files) that contain original source code. Developers frequently ship source
// maps to production, exposing server-side secrets embedded during bundling.
type SourceMapSource struct {
	BaseURL  string
	Registry *providers.Registry
	Limiters *recon.LimiterRegistry
	Client   *Client
}

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

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

// sourceMapResponse represents the top-level JSON of a .map file.
type sourceMapResponse struct {
	Sources        []string `json:"sources"`
	SourcesContent []string `json:"sourcesContent"`
}

// apiKeyPattern matches common API key patterns in source content.
var apiKeyPattern = regexp.MustCompile(`(?i)(api[_-]?key|secret|token|password|credential|auth)['":\s]*[=:]\s*['"]([a-zA-Z0-9_\-]{16,})['"]`)

// sourceMapPaths are common locations where source maps are served.
var sourceMapPaths = []string{
	"/static/js/main.js.map",
	"/static/js/bundle.js.map",
	"/assets/index.js.map",
	"/dist/bundle.js.map",
	"/main.js.map",
	"/app.js.map",
	"/_next/static/chunks/main.js.map",
}

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

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

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

		// Each query is used as a domain/URL hint; probe common map paths.
		for _, path := range sourceMapPaths {
			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 := base + path
			if base == "" {
				// Without a BaseURL we cannot construct real URLs; skip.
				continue
			}

			req, err := http.NewRequestWithContext(ctx, http.MethodGet, probeURL, nil)
			if err != nil {
				continue
			}
			req.Header.Set("Accept", "application/json")

			resp, err := client.Do(ctx, req)
			if err != nil {
				continue // 404s and other errors are expected during probing
			}

			var mapData sourceMapResponse
			if err := json.NewDecoder(resp.Body).Decode(&mapData); err != nil {
				_ = resp.Body.Close()
				continue
			}
			_ = resp.Body.Close()

			// Scan sourcesContent for API key patterns.
			for _, content := range mapData.SourcesContent {
				if apiKeyPattern.MatchString(content) {
					out <- recon.Finding{
						ProviderName: q,
						Source:       probeURL,
						SourceType:   "recon:sourcemaps",
						Confidence:   "medium",
						DetectedAt:   time.Now(),
					}
					break // one finding per map file is sufficient
				}
			}
		}
	}
	return nil
}
