package grpcli

import (
	"context"
	"errors"
	"fmt"
	"sync"

	"log"

	"github.com/tidbcloud/core-svc/idl/pbgen/proto/core"
	"github.com/tidbcloud/internal-portal/core-portal/central/config"
	"github.com/tidbcloud/tiinf/monitor/titracing"
	tigrpc "github.com/tidbcloud/tiinf/transport/tigrpc/client"
	"go.uber.org/zap"
)

var (
	coreSvcOnce sync.Once
	coreSvcCli  core.CoreServiceClient
)

const (
	coreComponentName = "internal-portal-core"
)

func getCoreSvcClient() core.CoreServiceClient {

	coreSvcOnce.Do(func() {
		_, err := titracing.InitJaeger(coreComponentName)
		if err != nil {
			log.Fatal(context.Background(), "failed to init core-svc tracing", zap.Error(err))
		}

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

		coreSvcCli = core.NewCoreServiceClient(conn)
	})

	return coreSvcCli
}

func ListClusters(ctx context.Context, req *core.ListClustersReq) (*core.ListClustersResp, error) {
	client := getCoreSvcClient()

	resp, e := client.ListClusters(ctx, req)
	if e != nil {
		return resp, e
	}
	if resp.BaseResp.ErrCode != 0 {
		return resp, errors.New(resp.BaseResp.ErrMsg)
	}
	return resp, nil
}

func GetCluster(ctx context.Context, req *core.ListClustersReq, clusterID uint64) (*core.Cluster, error) {
	clusters, err := ListClusters(ctx, req)
	if err != nil {
		return nil, err
	}

	cluster, ok := clusters.Clusters[clusterID]
	if !ok {
		return nil, errors.New(fmt.Sprintf("cluster is not found,id=%d", clusterID))
	}

	return cluster, nil
}
