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

// SwaggerHubSource searches published API definitions on SwaggerHub for
// embedded API keys in example values, server URLs, and security scheme
// defaults. The SwaggerHub specs API is publicly accessible.
type SwaggerHubSource struct {
	BaseURL  string
	Registry *providers.Registry
	Limiters *recon.LimiterRegistry
	Client   *Client
}

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

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

// swaggerHubSearchResult represents a single API from the search response.
type swaggerHubSearchResult struct {
	Name       string `json:"name"`
	URL        string `json:"url"`
	Properties []struct {
		Type string `json:"type"`
		URL  string `json:"url"`
	} `json:"properties"`
}

// swaggerHubSearchResponse is the top-level search response from SwaggerHub.
type swaggerHubSearchResponse struct {
	APIs []swaggerHubSearchResult `json:"apis"`
}

func (s *SwaggerHubSource) Sweep(ctx context.Context, query string, out chan<- recon.Finding) error {
	base := s.BaseURL
	if base == "" {
		base = "https://app.swaggerhub.com/apiproxy/specs"
	}
	client := s.Client
	if client == nil {
		client = NewClient()
	}

	queries := BuildQueries(s.Registry, "swaggerhub")
	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
			}
		}

		// Search public API specs.
		searchURL := fmt.Sprintf(
			"%s?specType=ANY&visibility=PUBLIC&query=%s&limit=10&page=1",
			base, url.QueryEscape(q),
		)

		req, err := http.NewRequestWithContext(ctx, http.MethodGet, searchURL, nil)
		if err != nil {
			continue
		}

		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 sr swaggerHubSearchResponse
		if err := json.Unmarshal(data, &sr); err != nil {
			continue
		}

		// Fetch each spec and scan for key patterns.
		for _, api := range sr.APIs {
			if err := ctx.Err(); err != nil {
				return err
			}

			specURL := api.URL
			if specURL == "" {
				// Fall back to the first property URL with type "Swagger" or "X-URL".
				for _, p := range api.Properties {
					if p.URL != "" {
						specURL = p.URL
						break
					}
				}
			}
			if specURL == "" {
				continue
			}

			if s.Limiters != nil {
				if err := s.Limiters.Wait(ctx, s.Name(), s.RateLimit(), s.Burst(), false); err != nil {
					return err
				}
			}

			specReq, err := http.NewRequestWithContext(ctx, http.MethodGet, specURL, nil)
			if err != nil {
				continue
			}

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

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

			if ciLogKeyPattern.Match(specData) {
				out <- recon.Finding{
					ProviderName: q,
					Source:       specURL,
					SourceType:   "recon:swaggerhub",
					Confidence:   "medium",
					DetectedAt:   time.Now(),
				}
			}
		}
	}
	return nil
}
