package cluster

import (
	"fmt"

	infra "github.com/tidbcloud/tidb-management-service/api/serverless_infra"
	"k8s.io/apimachinery/pkg/api/equality"
)

func (r *reconcileContext) updateProgress(phase infra.ClusterPhase, reason string) error {
	if r.cluster.Status.Phase == phase && r.cluster.Status.Reason == reason {
		return nil
	}

	r.Info("update cluster status event", "phase", phase, "reason", reason)

	if err := r.ensureStatus(func(status *infra.ClusterStatus) error {
		status.Phase = phase
		status.Reason = reason
		return nil
	}); err != nil {
		return fmt.Errorf("update progress err: %w", err)
	}

	return nil
}

// ensureStatus update the cluster status if necessary.
func (r *reconcileContext) ensureStatus(mutateFn func(clusterStatus *infra.ClusterStatus) error) error {
	old := r.cluster.Status.DeepCopy()

	if err := mutateFn(&r.cluster.Status); err != nil {
		return err
	}

	if equality.Semantic.DeepEqual(old, &r.cluster.Status) {
		// no changed, skip updating
		// Note: the local status may not be same as the truth,
		// but we will reach eventually-consistency via reconciliation
		return nil
	}

	return r.InfraClusterCli.Update(r.ctx, r.cluster)
}
