package importcfg

import (
	"fmt"

	corepb "github.com/tidbcloud/core-svc/idl/pbgen/proto/core"
	cloudv1 "github.com/tidbcloud/infra-api/api/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)

// The cr from coreCluster2Cr is only used for import getting config from gitops.
// Note: it is not the completed cr.
func coreCluster2Cr(cluster *corepb.Cluster) *cloudv1.Cluster {
	clusterCr := &cloudv1.Cluster{
		ObjectMeta: metav1.ObjectMeta{
			Name:      cluster.Name,
			Namespace: cluster.GetDataPlaneInfo().K8SNamespace,
			Labels: map[string]string{
				cloudv1.ProviderTypeLabel: cluster.InfraProviderType,
				cloudv1.TenantTagKey:      fmt.Sprintf("%d", cluster.TenantId),
				cloudv1.ProjectTagKey:     fmt.Sprintf("%d", cluster.ProjectId),
				cloudv1.ClusterTagKey:     fmt.Sprintf("%d", cluster.Id),
				cloudv1.RegionLabel:       cluster.RegionName,
			},
		},
		Spec: cloudv1.ClusterSpec{
			NetworkName: cluster.GetDataPlaneInfo().NetworkName,
		},
	}

	getReplicasAndInstanceType := func(tp corepb.ComponentType) (int, string) {
		for _, comp := range cluster.Components {
			if comp.ComponentType == tp {
				return int(comp.Replicas), comp.ComputeInstanceType
			}
		}
		if cluster.InfraProviderType == cloudv1.ProviderTypeAWSFreeTier {
			return 1, "aws_freetier_10"
		}
		return 0, ""
	}

	clusterCr.Spec.Cluster.TiDB.Replicas, clusterCr.Spec.Cluster.TiDB.InstanceType = getReplicasAndInstanceType(corepb.ComponentType_COMPONENT_TYPE_TIDB)
	clusterCr.Spec.Cluster.TiKV.Replicas, clusterCr.Spec.Cluster.TiKV.InstanceType = getReplicasAndInstanceType(corepb.ComponentType_COMPONENT_TYPE_TIKV)
	clusterCr.Spec.Cluster.PD.Replicas, clusterCr.Spec.Cluster.PD.InstanceType = getReplicasAndInstanceType(corepb.ComponentType_COMPONENT_TYPE_PD)
	clusterCr.Spec.Cluster.TiFlash.Replicas, clusterCr.Spec.Cluster.TiFlash.InstanceType = getReplicasAndInstanceType(corepb.ComponentType_COMPONENT_TYPE_TIFLASH)

	return clusterCr
}
