package common

import (
	"testing"

	"github.com/tidbcloud/infra-provider/regional-server/api/v1alpha1"
)

func TestNeedsMaintenanceHandshake(t *testing.T) {
	uo := &v1alpha1.UpgradeOperation{
		Spec: v1alpha1.UpgradeOperationSpec{
			MaintenancePolicyMode: v1alpha1.MaintenancePolicyModeClusterMaintenance,
		},
		Status: v1alpha1.UpgradeOperationStatus{
			CurrentStep: &v1alpha1.Step{Target: v1alpha1.TiDBNodes, Cluster: "42"},
		},
	}
	if !NeedsMaintenanceHandshake(uo) {
		t.Fatal("expected tidb-nodes step to require handshake")
	}

	uo.Status.CurrentStep.Target = v1alpha1.ControlPlane
	if NeedsMaintenanceHandshake(uo) {
		t.Fatal("expected controlplane step to skip handshake")
	}

	uo.Spec.MaintenancePolicyMode = v1alpha1.MaintenancePolicyModeLegacy
	uo.Status.CurrentStep.Target = v1alpha1.TiDBNodes
	if NeedsMaintenanceHandshake(uo) {
		t.Fatal("expected legacy mode to skip handshake")
	}
}

func TestMaintenanceAnnotationDone(t *testing.T) {
	raw := `{"spec":{"cluster_id":"42","time":"1"},"status":{"result":"done","time":"2"}}`
	done, err := maintenanceAnnotationDone(raw)
	if err != nil {
		t.Fatal(err)
	}
	if !done {
		t.Fatal("expected done annotation")
	}
}

func TestMaintenanceAnnotationStepIndex(t *testing.T) {
	idx, ok := MaintenanceAnnotationStepIndex(RequestStepAnnotationKey(5))
	if !ok || idx != 5 {
		t.Fatalf("step index = %d, ok = %v", idx, ok)
	}
}
