package grpc

import (
	"context"
	"dataapps/commons/config"
	"fmt"
	"sync"

	"github.com/tidbcloud/tiinf/monitor/tilog"
	"go.uber.org/zap"

	"github.com/tidbcloud/core-svc/idl/pbgen/proto/core"
	"github.com/tidbcloud/tiinf/errs"
	tigrpc "github.com/tidbcloud/tiinf/transport/tigrpc/client"
)

// @Time    : 2023/5/15 4:11 PM
// @Author  : lvhongmeng

var (
	coreSvcOnce sync.Once
	coreCli     core.CoreServiceClient

	excludeClusterStatus = []core.ClusterStatus{
		core.ClusterStatus_CLUSTER_STATUS_DELETED,
		core.ClusterStatus_CLUSTER_STATUS_DELETECOMPLETE,
		core.ClusterStatus_CLUSTER_STATUS_CLEARED,
	}
)

func getCoreSvcClient() core.CoreServiceClient {
	coreSvcOnce.Do(func() {

		conn, err := tigrpc.NewClientConn(
			config.Global().GrpcConfig.CoreSvcAddr,
			tigrpc.WithDefault(),
		)
		if err != nil {
			panic(fmt.Sprintf("Dial core-svc: %s", err))
		}

		coreCli = core.NewCoreServiceClient(conn)
	})

	return coreCli
}

func GetClusterById(ctx context.Context, clusterId uint64) (resp *core.Cluster, err error) {
	clusterInfos, err := GetClusterByIds(ctx, []uint64{clusterId})
	if err != nil {
		return nil, err
	}
	if clusterInfos[clusterId] == nil {
		return nil, errs.NewNotFound("cluster not exists", fmt.Errorf("cluster not exists: %d", clusterId))
	}
	return clusterInfos[clusterId], nil
}

func GetClusterByIds(ctx context.Context, clusterIds []uint64) (resp map[uint64]*core.Cluster, err error) {
	req := &core.ListClustersReq{
		Filter: &core.ClusterFilter{
			ClusterIds: clusterIds,
		},
	}

	res, err := ListClusters(ctx, req)
	if err != nil {
		return nil, err
	}
	return res.Clusters, nil

}

func ListClusters(ctx context.Context, req *core.ListClustersReq) (resp *core.ListClustersResp, err error) {

	client := getCoreSvcClient()

	resp, err = client.ListClusters(ctx, req)
	if err != nil {
		tilog.Error(ctx, "ERROR:rpc/core-svc:ListClusters failed", zap.Any("resp", resp), zap.Error(err))
		return nil, errs.NewInternalGRPC("get cluster info error!", err)
	}
	return resp, errs.ParseBaseResp(ctx, resp.BaseResp)
}
