package utils

import (
	"fmt"

	"github.com/pingcap/dbaas/central/config"
	"github.com/pingcap/dbaas/pkg/constants"
	tidbClusterV1alpha1 "github.com/pingcap/tidb-operator/pkg/apis/pingcap/v1alpha1"
	"github.com/pingcap/tidb-operator/pkg/controller"
	"k8s.io/apimachinery/pkg/api/errors"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/client-go/kubernetes"
)

func IsClusterInCreatingStatus(kubeCli kubernetes.Interface, tc *tidbClusterV1alpha1.TidbCluster) (bool, error) {
	if tc.Labels[constants.TiDBClusterStatusFromCentral] == string(constants.TidbClusterCreating) {
		return true, nil
	}
	initializerJob, err := kubeCli.BatchV1().Jobs(tc.GetNamespace()).Get(controller.TiDBInitializerMemberName(config.ClusterPrefix), metav1.GetOptions{})
	if err != nil {
		if errors.IsNotFound(err) {
			return false, nil
		}
		return true, fmt.Errorf("failed to get initializer job: %s", err.Error())
	}
	if initializerJob.Status.Succeeded == 0 {
		return true, nil
	}
	return false, nil
}
