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

// SlackSource discovers publicly indexed Slack messages that may contain
// leaked API keys. Slack workspaces occasionally have public archives, and
// search engines index shared Slack content. This source uses a dorking
// approach against a configurable search endpoint.
type SlackSource struct {
	BaseURL  string
	Registry *providers.Registry
	Limiters *recon.LimiterRegistry
	Client   *Client
}

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

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

// slackSearchResponse represents the search endpoint response for Slack dorking.
type slackSearchResponse struct {
	Results []slackSearchResult `json:"results"`
}

type slackSearchResult struct {
	URL     string `json:"url"`
	Content string `json:"content"`
}

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

	queries := BuildQueries(s.Registry, "slack")
	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?q=%s&format=json",
			base, url.QueryEscape("site:slack-archive.org OR site:slack-files.com "+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 slackSearchResponse
		if err := json.Unmarshal(body, &result); err != nil {
			continue
		}

		for _, item := range result.Results {
			if ciLogKeyPattern.MatchString(item.Content) {
				out <- recon.Finding{
					ProviderName: q,
					Source:       item.URL,
					SourceType:   "recon:slack",
					Confidence:   "low",
					DetectedAt:   time.Now(),
				}
			}
		}
	}
	return nil
}
