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

// VirusTotalSource searches the VirusTotal Intelligence API for files and URLs
// containing API key patterns. Malware samples frequently contain hard-coded
// API keys used by threat actors to exfiltrate data or proxy requests.
type VirusTotalSource struct {
	APIKey   string
	BaseURL  string
	Registry *providers.Registry
	Limiters *recon.LimiterRegistry
	Client   *Client
}

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

func (s *VirusTotalSource) Name() string         { return "virustotal" }
func (s *VirusTotalSource) RateLimit() rate.Limit { return rate.Every(15 * time.Second) }
func (s *VirusTotalSource) Burst() int            { return 2 }
func (s *VirusTotalSource) RespectsRobots() bool   { return false }
func (s *VirusTotalSource) Enabled(_ recon.Config) bool {
	return s.APIKey != ""
}

// vtSearchResponse represents the top-level VT intelligence search response.
type vtSearchResponse struct {
	Data []vtSearchItem `json:"data"`
}

// vtSearchItem is a single item in the VT search results.
type vtSearchItem struct {
	ID         string          `json:"id"`
	Attributes json.RawMessage `json:"attributes"`
}

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

	queries := BuildQueries(s.Registry, "virustotal")
	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/intelligence/search?query=%s&limit=10",
			base, url.QueryEscape(q),
		)
		req, err := http.NewRequestWithContext(ctx, http.MethodGet, searchURL, nil)
		if err != nil {
			continue
		}
		req.Header.Set("x-apikey", s.APIKey)

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

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

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

		for _, item := range result.Data {
			attrs := string(item.Attributes)
			if ciLogKeyPattern.MatchString(attrs) {
				out <- recon.Finding{
					ProviderName: q,
					Source:       fmt.Sprintf("https://www.virustotal.com/gui/file/%s", item.ID),
					SourceType:   "recon:virustotal",
					Confidence:   "medium",
					DetectedAt:   time.Now(),
				}
			}
		}
	}
	return nil
}
