package sources

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

	"golang.org/x/time/rate"

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

// KibanaSource searches exposed Kibana instances for API keys in saved objects
// such as dashboards, visualizations, and index patterns. Many Kibana instances
// are left unauthenticated, exposing the saved objects API.
type KibanaSource struct {
	BaseURL  string
	Registry *providers.Registry
	Limiters *recon.LimiterRegistry
	Client   *Client
}

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

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

// kibanaSavedObjectsResponse represents the Kibana saved objects API response.
type kibanaSavedObjectsResponse struct {
	SavedObjects []kibanaSavedObject `json:"saved_objects"`
}

type kibanaSavedObject struct {
	ID         string          `json:"id"`
	Type       string          `json:"type"`
	Attributes json.RawMessage `json:"attributes"`
}

func (s *KibanaSource) Sweep(ctx context.Context, query string, out chan<- recon.Finding) error {
	base := s.BaseURL
	if base == "" {
		base = "http://localhost:5601"
	}
	client := s.Client
	if client == nil {
		client = NewClient()
	}

	queries := BuildQueries(s.Registry, "kibana")
	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
			}
		}

		// Search saved objects (dashboards and visualizations).
		searchURL := fmt.Sprintf(
			"%s/api/saved_objects/_find?type=visualization&type=dashboard&search=%s&per_page=20",
			base, url.QueryEscape(q),
		)
		req, err := http.NewRequestWithContext(ctx, http.MethodGet, searchURL, nil)
		if err != nil {
			continue
		}
		req.Header.Set("kbn-xsrf", "true")

		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 kibanaSavedObjectsResponse
		if err := json.Unmarshal(data, &result); err != nil {
			continue
		}

		for _, obj := range result.SavedObjects {
			attrs := string(obj.Attributes)
			if ciLogKeyPattern.MatchString(attrs) {
				out <- recon.Finding{
					ProviderName: q,
					Source:       fmt.Sprintf("%s/app/kibana#/%s/%s", base, obj.Type, obj.ID),
					SourceType:   "recon:kibana",
					Confidence:   "medium",
					DetectedAt:   time.Now(),
				}
			}
		}
	}
	return nil
}
