package cvt

import (
	"testing"

	cloudv1 "github.com/tidbcloud/infra-api/api/v1"
	apiv1 "github.com/tidbcloud/infra-provider/api/tidbcloud/cluster-server/v1"
)

func buildTestCluster(suspendAction *cloudv1.SuspendAction, phase cloudv1.ClusterPhase, suspendedStatus cloudv1.ConditionStatus) *cloudv1.Cluster {
	return &cloudv1.Cluster{
		Spec: cloudv1.ClusterSpec{
			Cluster: cloudv1.ClusterTopology{
				SuspendAction: suspendAction,
			},
		},
		Status: cloudv1.ClusterStatus{
			Phase: phase,
			Conditions: []cloudv1.ClusterCondition{
				{
					Type:   cloudv1.ClusterSuspended,
					Status: suspendedStatus,
				},
			},
		},
	}
}

func TestCalculateClusterPhase(t *testing.T) {
	tests := []struct {
		name    string
		cluster *cloudv1.Cluster
		want    apiv1.Cluster_ClusterPhase
	}{
		{
			name:    "pause a cluster",
			cluster: buildTestCluster(&cloudv1.SuspendAction{SuspendCompute: true}, cloudv1.ClusterPhaseRunning, cloudv1.ConditionFalse),
			want:    apiv1.Cluster_SYNCING,
		},
		{
			name:    "cluster is pausing",
			cluster: buildTestCluster(&cloudv1.SuspendAction{SuspendCompute: true}, cloudv1.ClusterPhaseSuspend, cloudv1.ConditionFalse),
			want:    apiv1.Cluster_SYNCING,
		},
		{
			name:    "cluster is paused",
			cluster: buildTestCluster(&cloudv1.SuspendAction{SuspendCompute: true}, cloudv1.ClusterPhaseSuspend, cloudv1.ConditionTrue),
			want:    apiv1.Cluster_SYNCED,
		},
		{
			name:    "resume a cluster",
			cluster: buildTestCluster(&cloudv1.SuspendAction{SuspendCompute: false}, cloudv1.ClusterPhaseSuspend, cloudv1.ConditionTrue),
			want:    apiv1.Cluster_SYNCING,
		},
		{
			name:    "cluster is resuming",
			cluster: buildTestCluster(&cloudv1.SuspendAction{SuspendCompute: false}, cloudv1.ClusterPhaseSuspend, cloudv1.ConditionFalse),
			want:    apiv1.Cluster_SYNCING,
		},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			if got := CalculateClusterPhase(tt.cluster); got != tt.want {
				t.Errorf("CalculateClusterPhase() = %v, want %v", got, tt.want)
			}
		})
	}
}
