package sources

import (
	"context"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"net/url"
	"strings"
	"time"

	"golang.org/x/time/rate"

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

// SplunkSource searches exposed Splunk instances for API keys in log data.
// Exposed Splunk Web interfaces may allow unauthenticated search via the
// REST API, especially in development or misconfigured environments.
type SplunkSource struct {
	BaseURL  string
	Registry *providers.Registry
	Limiters *recon.LimiterRegistry
	Client   *Client
}

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

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

// splunkResult represents a single result row from Splunk search export.
type splunkResult struct {
	Result json.RawMessage `json:"result"`
	Raw    string          `json:"_raw"`
}

func (s *SplunkSource) Sweep(ctx context.Context, query string, out chan<- recon.Finding) error {
	base := s.BaseURL
	if base == "" {
		base = "https://localhost:8089"
	}
	// If no explicit target was provided (still default) and query is not a URL, skip.
	if base == "https://localhost:8089" && query != "" && !strings.HasPrefix(query, "http") {
		return nil
	}
	client := s.Client
	if client == nil {
		client = NewClient()
	}

	queries := BuildQueries(s.Registry, "splunk")
	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/services/search/jobs/export?search=%s&output_mode=json&count=20",
			base, url.QueryEscape("search "+q),
		)
		req, err := http.NewRequestWithContext(ctx, http.MethodGet, searchURL, nil)
		if err != nil {
			continue
		}

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

		data, err := io.ReadAll(io.LimitReader(resp.Body, 512*1024))
		_ = resp.Body.Close()
		if err != nil {
			continue
		}

		// Splunk export returns newline-delimited JSON objects.
		for _, line := range strings.Split(string(data), "\n") {
			line = strings.TrimSpace(line)
			if line == "" {
				continue
			}

			var sr splunkResult
			if err := json.Unmarshal([]byte(line), &sr); err != nil {
				continue
			}

			content := sr.Raw
			if content == "" {
				content = string(sr.Result)
			}

			if ciLogKeyPattern.MatchString(content) {
				out <- recon.Finding{
					ProviderName: q,
					Source:       fmt.Sprintf("%s/services/search/jobs/export", base),
					SourceType:   "recon:splunk",
					Confidence:   "medium",
					DetectedAt:   time.Now(),
				}
			}
		}
	}
	return nil
}
