package agentk

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"log/slog"
	"net/http"
	"slices"

	"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v18/internal/module/modagent"
	"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v18/internal/tool/errz"
	"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v18/internal/tool/ioz"
	"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v18/internal/tool/logz"
	"gitlab.com/gitlab-org/security-products/analyzers/trivy-k8s-wrapper/data/analyzers/report"
)

type requestType string

const (
	requestTypeCreateVulnerability   requestType = "create starboard vulnerability"
	requestTypeResolveVulnerability  requestType = "resolve starboard vulnerability"
	vulnerabilityResolutionBatchSize int         = 250
)

type Reporter interface {
	Transmit(ctx context.Context, payloads []*Payload) ([]string, error)
	createVulnerability(ctx context.Context, payload *Payload) (uuid string, retError error)
	ResolveVulnerabilities(ctx context.Context, uuids []string) (retError error)
}

type reporter struct {
	log *slog.Logger
	api modagent.API
}

type uuidResponse struct {
	UUID string `json:"uuid"`
}

type reqBody struct {
	UUIDs []string `json:"uuids"`
}

func newReporter(log *slog.Logger, api modagent.API) *reporter {
	return &reporter{
		log: log,
		api: api,
	}
}

func (r *reporter) Transmit(ctx context.Context, payloads []*Payload) ([]string, error) {
	uuids := make([]string, 0, len(payloads))

	// If at least one of the detected vulnerabilities fails to create, don't
	// resolve vulnerabilities. Potentially all detected vulnerabilities might
	// fail to create, and in turn all previously detected vulnerabilities would
	// get resolved otherwise.
	var errs []error

	r.log.Info("Creating vulnerabilities in GitLab", logz.VulnerabilitiesCount(len(payloads)))
	for _, payload := range payloads {
		uuid, err := r.createVulnerability(ctx, payload)
		if err != nil {
			errs = append(errs, fmt.Errorf("creating vulnerability identifier: %s: %w", vulnPrimaryIdentifier(payload.Vulnerability), err))
			continue
		}
		uuids = append(uuids, uuid)
	}

	if len(errs) > 0 {
		r.log.Warn("Some vulnerabilities failed to create, skipping vulnerability resolution")
		return nil, errors.Join(errs...)
	}
	if len(uuids) == 0 {
		r.log.Debug("No UUIDs collected, nothing to resolve")
		return nil, nil
	}

	return uuids, nil
}

func (r *reporter) createVulnerability(ctx context.Context, payload *Payload) (uuid string, retError error) {
	resp, err := r.api.MakeGitLabRequest(ctx, "/",
		modagent.WithRequestMethod(http.MethodPut),
		modagent.WithJSONRequestBody(payload),
	)
	if err != nil {
		return "", fmt.Errorf("error making api request: %w", err)
	}
	defer errz.SafeClose(resp.Body, &retError)
	if resp.StatusCode != http.StatusOK {
		return "", handleAPIError(requestTypeCreateVulnerability, resp)
	}

	var uuidResp uuidResponse
	err = ioz.ReadAllFunc(resp.Body, func(body []byte) error {
		return json.Unmarshal(body, &uuidResp)
	})
	if err != nil {
		return "", fmt.Errorf("response body: %w", err)
	}
	return uuidResp.UUID, nil
}

func (r *reporter) ResolveVulnerabilities(ctx context.Context, uuids []string) (retError error) {
	for batch := range slices.Chunk(uuids, vulnerabilityResolutionBatchSize) {
		r.log.Debug("Resolving vulnerabilities batch", logz.VulnerabilitiesCount(len(batch)))

		if err := r.resolveVulnerabilitiesBatch(ctx, batch); err != nil {
			return err
		}
	}

	return nil
}

func (r *reporter) resolveVulnerabilitiesBatch(ctx context.Context, uuids []string) (retError error) {
	resp, err := r.api.MakeGitLabRequest(ctx, "/scan_result",
		modagent.WithRequestMethod(http.MethodPost),
		modagent.WithJSONRequestBody(reqBody{
			UUIDs: uuids,
		}),
	)
	if err != nil {
		return fmt.Errorf("error making api request: %w", err)
	}
	defer errz.SafeClose(resp.Body, &retError)

	if resp.StatusCode != http.StatusOK {
		return handleAPIError(requestTypeResolveVulnerability, resp)
	}

	return nil
}

func vulnPrimaryIdentifier(vuln *report.Vulnerability) string {
	if len(vuln.Identifiers) == 0 {
		return "unknown"
	}

	return vuln.Identifiers[0].Value
}

type apiError struct {
	Error string `json:"error"`
}

func handleAPIError(typ requestType, resp *modagent.GitLabResponse) error {
	var errResp apiError
	err := ioz.ReadAllFunc(resp.Body, func(body []byte) error {
		return json.Unmarshal(body, &errResp)
	})
	if err != nil {
		return fmt.Errorf("could not read api response status: %d: %w", resp.StatusCode, err)
	}
	return fmt.Errorf("%s api request failed with status: %d message: %s", typ, resp.StatusCode, errResp.Error)
}
