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

// DiscordSource discovers Discord content indexed by search engines that may
// contain leaked API keys. Discord has no public message search API, so this
// source uses a dorking approach against a configurable search endpoint to
// find Discord content cached by third-party indexers.
type DiscordSource struct {
	BaseURL  string
	Registry *providers.Registry
	Limiters *recon.LimiterRegistry
	Client   *Client
}

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

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

// discordSearchResponse represents the search endpoint response for Discord dorking.
type discordSearchResponse struct {
	Results []discordSearchResult `json:"results"`
}

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

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

	queries := BuildQueries(s.Registry, "discord")
	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:discord.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 discordSearchResponse
		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:discord",
					Confidence:   "low",
					DetectedAt:   time.Now(),
				}
			}
		}
	}
	return nil
}
