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

// TrelloSource searches public Trello boards for leaked API keys.
// Trello public boards are searchable without authentication, and developers
// often paste credentials into card descriptions or comments.
type TrelloSource struct {
	BaseURL  string
	Registry *providers.Registry
	Limiters *recon.LimiterRegistry
	Client   *Client
}

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

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

// trelloSearchResponse represents the Trello search API response.
type trelloSearchResponse struct {
	Cards []trelloCard `json:"cards"`
}

type trelloCard struct {
	ID   string `json:"id"`
	Name string `json:"name"`
	Desc string `json:"desc"`
}

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

	queries := BuildQueries(s.Registry, "trello")
	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/1/search?query=%s&modelTypes=cards&card_fields=name,desc&cards_limit=10",
			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 trelloSearchResponse
		if err := json.Unmarshal(body, &result); err != nil {
			continue
		}

		for _, card := range result.Cards {
			if ciLogKeyPattern.MatchString(card.Desc) {
				out <- recon.Finding{
					ProviderName: q,
					Source:       fmt.Sprintf("https://trello.com/c/%s", card.ID),
					SourceType:   "recon:trello",
					Confidence:   "medium",
					DetectedAt:   time.Now(),
				}
			}
		}
	}
	return nil
}
