package automation

import (
	"context"
	"fmt"
	"net/http"
	"net/url"
	"strings"

	"github.com/tidbcloud/AgentTeam/internal/service/automation/runtime"
)

// AGSHTTPAutomationRepoStatusWriter writes automation run states to embedded AGS
// commit statuses using MeshX internal authorization.
type AGSHTTPAutomationRepoStatusWriter struct {
	Handler             http.Handler
	AuthHeader          string
	AuthorizationHeader string
}

func (w AGSHTTPAutomationRepoStatusWriter) CreateCommitStatus(ctx context.Context, req runtime.AutomationCommitStatusRequest) error {
	if w.Handler == nil {
		return invalidArgument("AGS automation repo status writer is not configured")
	}
	if strings.TrimSpace(w.AuthorizationHeader) == "" {
		return unauthorized("Authorization is required to write automation repo status")
	}
	owner := strings.TrimSpace(req.RepositoryOwner)
	repo := strings.TrimSpace(req.RepositoryName)
	sha := strings.TrimSpace(req.CommitSHA)
	if owner == "" || repo == "" || sha == "" {
		return invalidArgument("repository owner, repository name, and commit SHA are required")
	}
	payload := map[string]string{
		"state":       strings.TrimSpace(req.State),
		"context":     strings.TrimSpace(req.Context),
		"description": strings.TrimSpace(req.Description),
		"target_url":  strings.TrimSpace(req.TargetURL),
	}
	response := doAGSInternalJSONRequest(ctx, w.Handler, w.AuthHeader, w.AuthorizationHeader, http.MethodPost, "/api/v3/repos/"+url.PathEscape(owner)+"/"+url.PathEscape(repo)+"/statuses/"+url.PathEscape(sha), payload)
	if response.Code < 200 || response.Code >= 300 {
		return fmt.Errorf("create AGS automation commit status: status %d: %s", response.Code, strings.TrimSpace(response.Body.String()))
	}
	return nil
}
