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

// StackOverflowSource searches Stack Exchange API for questions and answers
// containing leaked API keys. Developers frequently paste credentials in
// code examples when asking for help debugging API integrations.
type StackOverflowSource struct {
	BaseURL  string
	Registry *providers.Registry
	Limiters *recon.LimiterRegistry
	Client   *Client
}

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

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

// stackExchangeResponse represents the Stack Exchange API v2.3 search/excerpts response.
type stackExchangeResponse struct {
	Items []stackExchangeItem `json:"items"`
}

type stackExchangeItem struct {
	Body      string `json:"body"`
	Excerpt   string `json:"excerpt"`
	QuestionID int   `json:"question_id"`
}

func (s *StackOverflowSource) Sweep(ctx context.Context, _ string, out chan<- recon.Finding) error {
	base := s.BaseURL
	if base == "" {
		base = "https://api.stackexchange.com"
	}
	client := s.Client
	if client == nil {
		client = NewClient()
	}

	queries := BuildQueries(s.Registry, "stackoverflow")
	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/2.3/search/excerpts?order=desc&sort=relevance&q=%s&site=stackoverflow",
			base, url.QueryEscape(q))
		req, err := http.NewRequestWithContext(ctx, http.MethodGet, searchURL, nil)
		if err != nil {
			continue
		}
		req.Header.Set("Accept", "application/json")

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

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

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

		for _, item := range result.Items {
			content := item.Body + " " + item.Excerpt
			if ciLogKeyPattern.MatchString(content) {
				itemURL := fmt.Sprintf("https://stackoverflow.com/q/%d", item.QuestionID)
				out <- recon.Finding{
					ProviderName: q,
					Source:       itemURL,
					SourceType:   "recon:stackoverflow",
					Confidence:   "medium",
					DetectedAt:   time.Now(),
				}
			}
		}
	}
	return nil
}
