package sources

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

	"golang.org/x/time/rate"

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

// DeployPreviewSource scans Vercel and Netlify deploy preview URLs for leaked
// API keys. Deploy previews frequently use different (less restrictive)
// environment variables than production, and their URLs are often guessable
// from PR numbers or commit hashes.
type DeployPreviewSource struct {
	BaseURL  string
	Registry *providers.Registry
	Limiters *recon.LimiterRegistry
	Client   *Client
}

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

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

// deployPreviewPaths are paths where deploy previews expose build artifacts.
var deployPreviewPaths = []string{
	"/",
	"/_next/data/",
	"/static/js/main.js",
	"/__nextjs_original-stack-frame",
}

// nextDataPattern matches __NEXT_DATA__ script blocks and inline env vars.
var nextDataPattern = regexp.MustCompile(`(?i)(__NEXT_DATA__|NEXT_PUBLIC_|REACT_APP_|VITE_)[A-Z_]*(API[_]?KEY|SECRET|TOKEN)?['":\s]*[=:,]\s*['"]([a-zA-Z0-9_\-]{8,})['"]`)

func (s *DeployPreviewSource) 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, "deploypreview")
	if len(queries) == 0 {
		return nil
	}

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

		for _, path := range deployPreviewPaths {
			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
			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, 512*1024))
			_ = resp.Body.Close()
			if err != nil {
				continue
			}

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