package grpc

// @Time    : 2022/11/14 4:47 PM
// @Author  : lvhongmeng

import (
	"context"
	"fmt"
	"message-service/commons/config"
	"message-service/commons/utils"
	"sync"

	"github.com/tidbcloud/dataservices/idl/pbgen/proto/dataapi"
	"github.com/tidbcloud/tiinf/errs"
	"github.com/tidbcloud/tiinf/monitor/tilog"
	tigrpc "github.com/tidbcloud/tiinf/transport/tigrpc/client"
)

var (
	dataAPISvcOnce sync.Once
	dataAPISvcCli  dataapi.DataAPIServiceClient
)

func getDataAPISvcClient() dataapi.DataAPIServiceClient {
	dataAPISvcOnce.Do(func() {
		conn, err := tigrpc.NewClientConn(config.Global().GrpcConf.DataAPISvcAddr, tigrpc.WithDefault())
		if err != nil {
			panic(fmt.Sprintf("dial dataapi-svc: %s", err))
		}

		dataAPISvcCli = dataapi.NewDataAPIServiceClient(conn)
	})

	return dataAPISvcCli
}

func GetDatabaseMeta(ctx context.Context, req *dataapi.GetDatabaseMetaReq) (*dataapi.GetDatabaseMetaResp, error) {
	client := getDataAPISvcClient()

	tilog.Info(ctx, fmt.Sprintf("rpc/dataapi:GetDatabaseMeta begin! payload:%+v", req))
	resp, e := client.GetDatabaseMeta(ctx, req)
	tilog.Info(ctx, fmt.Sprintf("rpc/dataapi:GetDatabaseMeta complete! resp:%+v, err:%+v", resp, e))
	if e != nil {
		return resp, errs.NewInternalGRPC(utils.GetFuncName(), e)
	}
	return resp, formatError(ctx, e, resp.BaseResp)
}

func GetClusterMeta(ctx context.Context, req *dataapi.GetClusterMetaReq) (*dataapi.GetClusterMetaResp, error) {
	client := getDataAPISvcClient()

	tilog.Info(ctx, fmt.Sprintf("rpc/dataapi:GetDatabaseMeta begin!payload:%+v", req))
	resp, e := client.GetClusterMeta(ctx, req)
	if e != nil {
		return resp, errs.NewInternalGRPC(utils.GetFuncName(), e)
	}
	return resp, formatError(ctx, e, resp.BaseResp)
}
