package ops_svc

import (
	"testing"

	"github.com/stretchr/testify/require"
	tidbmgmtservicev1 "github.com/tidbcloud/tidb-management-service/api/spec/tidb_mgmt_service/v1"
)

func TestToClusterCDCJobInfo_LegacyClusterLock(t *testing.T) {
	// The old-arch cluster-level lock: CDC-typed, self-mutexing against CDC.
	status := &tidbmgmtservicev1.ClusterCustomStatus{
		StatusId:   100,
		StatusName: "cdc-1001-1700000000",
		StatusType: tidbmgmtservicev1.CustomStatusType_CUSTOM_STATUS_TYPE_CDC,
		Mutex: &tidbmgmtservicev1.ClusterCustomStatus_CustomMutex{
			StatusType: []tidbmgmtservicev1.CustomStatusType{
				tidbmgmtservicev1.CustomStatusType_CUSTOM_STATUS_TYPE_IMPORT,
				tidbmgmtservicev1.CustomStatusType_CUSTOM_STATUS_TYPE_SERVERLESS_RESTORE_INPLACE,
				tidbmgmtservicev1.CustomStatusType_CUSTOM_STATUS_TYPE_CDC,
			},
			ClusterAction: []tidbmgmtservicev1.ClusterAction{
				tidbmgmtservicev1.ClusterAction_CLUSTER_ACTION_DELETE_CLUSTER,
			},
		},
	}

	info := toClusterCDCJobInfo(status)
	require.Equal(t, "100", info.GetStatusId())
	require.True(t, info.GetIsLegacyClusterLock())
	require.False(t, info.GetIsExpired())
	require.Contains(t, info.GetMutexStatusTypes(), "CUSTOM_STATUS_TYPE_CDC")
	require.Contains(t, info.GetMutexClusterActions(), "CLUSTER_ACTION_DELETE_CLUSTER")
}

func TestToClusterCDCJobInfo_PerChangefeedJob(t *testing.T) {
	// A newarch per-changefeed job: CDC-typed but with an empty status mutex.
	status := &tidbmgmtservicev1.ClusterCustomStatus{
		StatusId:   200,
		StatusName: "cf-abc",
		StatusType: tidbmgmtservicev1.CustomStatusType_CUSTOM_STATUS_TYPE_CDC,
		Mutex: &tidbmgmtservicev1.ClusterCustomStatus_CustomMutex{
			ClusterAction: []tidbmgmtservicev1.ClusterAction{
				tidbmgmtservicev1.ClusterAction_CLUSTER_ACTION_DELETE_CLUSTER,
				tidbmgmtservicev1.ClusterAction_CLUSTER_ACTION_PAUSE_CLUSTER,
			},
		},
	}

	info := toClusterCDCJobInfo(status)
	require.Equal(t, "200", info.GetStatusId())
	require.False(t, info.GetIsLegacyClusterLock())
}

func TestToClusterCDCJobInfo_ExpiredLegacyLockNotFlagged(t *testing.T) {
	status := &tidbmgmtservicev1.ClusterCustomStatus{
		StatusId:   300,
		StatusType: tidbmgmtservicev1.CustomStatusType_CUSTOM_STATUS_TYPE_CDC,
		IsExpired:  true,
		Mutex: &tidbmgmtservicev1.ClusterCustomStatus_CustomMutex{
			StatusType: []tidbmgmtservicev1.CustomStatusType{
				tidbmgmtservicev1.CustomStatusType_CUSTOM_STATUS_TYPE_CDC,
			},
		},
	}

	info := toClusterCDCJobInfo(status)
	require.True(t, info.GetIsExpired())
	require.False(t, info.GetIsLegacyClusterLock())
}
