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

// HackerNewsSource searches the Algolia-powered Hacker News search API for
// comments containing leaked API keys. Developers occasionally paste
// credentials in HN discussion threads about APIs and tools.
type HackerNewsSource struct {
	BaseURL  string
	Registry *providers.Registry
	Limiters *recon.LimiterRegistry
	Client   *Client
}

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

func (s *HackerNewsSource) Name() string               { return "hackernews" }
func (s *HackerNewsSource) RateLimit() rate.Limit       { return rate.Every(1 * time.Second) }
func (s *HackerNewsSource) Burst() int                  { return 5 }
func (s *HackerNewsSource) RespectsRobots() bool        { return false }
func (s *HackerNewsSource) Enabled(_ recon.Config) bool { return true }

// hnSearchResponse represents the Algolia HN Search API response.
type hnSearchResponse struct {
	Hits []hnHit `json:"hits"`
}

type hnHit struct {
	CommentText string `json:"comment_text"`
	ObjectID    string `json:"objectID"`
	StoryID     int    `json:"story_id"`
}

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

	queries := BuildQueries(s.Registry, "hackernews")
	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/api/v1/search?query=%s&tags=comment&hitsPerPage=20",
			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 hnSearchResponse
		if err := json.Unmarshal(body, &result); err != nil {
			continue
		}

		for _, hit := range result.Hits {
			if ciLogKeyPattern.MatchString(hit.CommentText) {
				itemURL := fmt.Sprintf("https://news.ycombinator.com/item?id=%s", hit.ObjectID)
				out <- recon.Finding{
					ProviderName: q,
					Source:       itemURL,
					SourceType:   "recon:hackernews",
					Confidence:   "medium",
					DetectedAt:   time.Now(),
				}
			}
		}
	}
	return nil
}
