package sources

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

	"golang.org/x/time/rate"

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

// ElasticsearchSource searches exposed Elasticsearch instances for documents
// containing API keys. Many ES deployments are left unauthenticated on the
// internet, allowing full-text search across all indexed data.
type ElasticsearchSource struct {
	BaseURL  string
	Registry *providers.Registry
	Limiters *recon.LimiterRegistry
	Client   *Client
}

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

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

// esSearchResponse represents the Elasticsearch _search response envelope.
type esSearchResponse struct {
	Hits struct {
		Hits []esHit `json:"hits"`
	} `json:"hits"`
}

type esHit struct {
	Index  string          `json:"_index"`
	ID     string          `json:"_id"`
	Source json.RawMessage `json:"_source"`
}

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

	queries := BuildQueries(s.Registry, "elasticsearch")
	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/_search", base)
		body := fmt.Sprintf(`{"query":{"query_string":{"query":"%s"}},"size":20}`, q)
		req, err := http.NewRequestWithContext(ctx, http.MethodPost, searchURL, bytes.NewBufferString(body))
		if err != nil {
			continue
		}
		req.Header.Set("Content-Type", "application/json")

		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
		}

		var result esSearchResponse
		if err := json.Unmarshal(data, &result); err != nil {
			continue
		}

		for _, hit := range result.Hits.Hits {
			src := string(hit.Source)
			if ciLogKeyPattern.MatchString(src) {
				out <- recon.Finding{
					ProviderName: q,
					Source:       fmt.Sprintf("%s/%s/%s", base, hit.Index, hit.ID),
					SourceType:   "recon:elasticsearch",
					Confidence:   "medium",
					DetectedAt:   time.Now(),
				}
			}
		}
	}
	return nil
}
