package staticsite

import (
	"context"
	"log/slog"
)

// CommitStatusReporter pushes deploy outcomes back to the git provider as a
// commit status, gated on the per-workload report_commit_status flag. It is
// strictly best-effort: every call is wrapped so a reporting failure is logged
// at Warn and NEVER propagates to fail or block the deploy.
//
// The provider + identifiers are captured once at deploy start so the hot
// transition points (pending/success/failure) read as one-liners. A nil
// receiver (reporting disabled) makes Report a no-op, so callers don't have to
// guard each transition.
//
// It lives in the staticsite package (alongside GitProvider / CommitStatus)
// rather than the plugin package so the source plugins can share it without
// staticsite taking a dependency on plugin. It is parameterized on primitives
// (not plugin.Workload) for the same reason.
type CommitStatusReporter struct {
	provider  GitProvider
	owner     string
	repo      string
	sha       string
	targetURL string
	enabled   bool
}

// NewCommitStatusReporter builds a reporter from the resolved deploy inputs.
// When enabled is false (report_commit_status off) or the SHA is empty, the
// returned reporter's Report method is inert.
func NewCommitStatusReporter(provider GitProvider, owner, repo, sha, targetURL string, enabled bool) *CommitStatusReporter {
	return &CommitStatusReporter{
		provider:  provider,
		owner:     owner,
		repo:      repo,
		sha:       sha,
		targetURL: targetURL,
		enabled:   enabled,
	}
}

// Report sends one commit status, swallowing (and logging) any error. Safe to
// call on a nil/disabled reporter or with a nil provider/empty SHA.
func (r *CommitStatusReporter) Report(ctx context.Context, workloadName, workloadID string, status CommitStatus, description string) {
	if r == nil || !r.enabled || r.provider == nil || r.sha == "" {
		return
	}
	if err := r.provider.SetCommitStatus(ctx, r.owner, r.repo, r.sha, status, r.targetURL, description); err != nil {
		slog.Warn("commit-status report failed (ignored)",
			"workload", workloadName, "workload_id", workloadID, "status", string(status), "error", err)
	}
}
