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"
)

// GrafanaSource searches exposed Grafana instances for API keys in dashboard
// configurations, panel queries, and data source settings. Many Grafana
// deployments enable anonymous access, exposing dashboards publicly.
type GrafanaSource struct {
	BaseURL  string
	Registry *providers.Registry
	Limiters *recon.LimiterRegistry
	Client   *Client
}

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

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

// grafanaSearchResult represents a Grafana dashboard search result.
type grafanaSearchResult struct {
	UID   string `json:"uid"`
	Title string `json:"title"`
}

// grafanaDashboardResponse represents the full dashboard detail response.
type grafanaDashboardResponse struct {
	Dashboard json.RawMessage `json:"dashboard"`
}

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

	queries := BuildQueries(s.Registry, "grafana")
	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 for dashboards matching keyword.
		searchURL := fmt.Sprintf(
			"%s/api/search?query=%s&type=dash-db&limit=10",
			base, url.QueryEscape(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
		}

		var results []grafanaSearchResult
		if err := json.Unmarshal(data, &results); err != nil {
			continue
		}

		// Fetch each dashboard detail and scan for keys.
		for _, dash := range results {
			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
				}
			}

			dashURL := fmt.Sprintf("%s/api/dashboards/uid/%s", base, dash.UID)
			dashReq, err := http.NewRequestWithContext(ctx, http.MethodGet, dashURL, nil)
			if err != nil {
				continue
			}

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

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

			if ciLogKeyPattern.Match(dashData) {
				out <- recon.Finding{
					ProviderName: q,
					Source:       fmt.Sprintf("%s/d/%s/%s", base, dash.UID, dash.Title),
					SourceType:   "recon:grafana",
					Confidence:   "medium",
					DetectedAt:   time.Now(),
				}
			}
		}
	}
	return nil
}
