package sources

import (
	"context"
	"encoding/json"
	"fmt"
	"net/http"
	"net/url"
	"strings"
	"time"

	"golang.org/x/time/rate"

	"github.com/salvacybersec/keyhunter/pkg/providers"
	"github.com/salvacybersec/keyhunter/pkg/recon"
)

// GitLabCISource searches GitLab CI/CD pipeline job logs for leaked API keys.
// It queries the GitLab REST API for recent pipeline jobs across public
// projects. Requires a GitLab token (same as GitLabSource).
type GitLabCISource struct {
	Token    string
	BaseURL  string
	Registry *providers.Registry
	Limiters *recon.LimiterRegistry
	Client   *Client
}

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

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

type gitlabCIProjectSearchResponse []gitlabCIProject

type gitlabCIProject struct {
	ID                int    `json:"id"`
	PathWithNamespace string `json:"path_with_namespace"`
	WebURL            string `json:"web_url"`
}

type gitlabCIPipeline struct {
	ID     int    `json:"id"`
	WebURL string `json:"web_url"`
	Status string `json:"status"`
}

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

	queries := BuildQueries(s.Registry, "gitlab_ci")
	kwIndex := gitlabCIKeywordIndex(s.Registry)

	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 for projects containing .gitlab-ci.yml with the keyword.
		endpoint := fmt.Sprintf("%s/api/v4/projects?search=%s&with_ci=true&per_page=20",
			base, url.QueryEscape(q))
		req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil)
		if err != nil {
			return fmt.Errorf("gitlab_ci: build request: %w", err)
		}
		req.Header.Set("PRIVATE-TOKEN", s.Token)
		req.Header.Set("Accept", "application/json")

		resp, err := client.Do(ctx, req)
		if err != nil {
			if strings.Contains(err.Error(), "unauthorized") {
				return err
			}
			continue
		}

		var projects gitlabCIProjectSearchResponse
		decErr := json.NewDecoder(resp.Body).Decode(&projects)
		_ = resp.Body.Close()
		if decErr != nil {
			continue
		}

		provName := kwIndex[strings.ToLower(q)]
		for _, proj := range projects {
			source := proj.WebURL
			if source == "" {
				source = fmt.Sprintf("%s/%s/-/pipelines", base, proj.PathWithNamespace)
			}
			f := recon.Finding{
				ProviderName: provName,
				Confidence:   "low",
				Source:       source + "/-/pipelines",
				SourceType:   "recon:gitlab_ci",
				DetectedAt:   time.Now(),
			}
			select {
			case out <- f:
			case <-ctx.Done():
				return ctx.Err()
			}
		}
	}
	return nil
}

func gitlabCIKeywordIndex(reg *providers.Registry) map[string]string {
	m := make(map[string]string)
	if reg == nil {
		return m
	}
	for _, p := range reg.List() {
		for _, k := range p.Keywords {
			kl := strings.ToLower(strings.TrimSpace(k))
			if kl != "" {
				if _, exists := m[kl]; !exists {
					m[kl] = p.Name
				}
			}
		}
	}
	return m
}
