package grpc

import (
	"context"
	"dataservices/commons/config"
	"fmt"
	"sync"
	"time"

	"github.com/tidbcloud/dataapps/idl/pbgen/proto/sqleditor"
	tierr "github.com/tidbcloud/tiinf/errs"
	"github.com/tidbcloud/tiinf/monitor/tilog"
	tigrpc "github.com/tidbcloud/tiinf/transport/tigrpc/client"
	"go.uber.org/zap"
)

var (
	sqleditorInitOnce sync.Once
	sqleditorCli      sqleditor.SqlEditorServiceClient
)

func getSqleditorClient() sqleditor.SqlEditorServiceClient {
	sqleditorInitOnce.Do(func() {
		conn, err := tigrpc.NewClientConn(config.Global().GrpcConf.SqleditorAddr, tigrpc.WithDefault())
		if err != nil {
			panic(fmt.Sprintf("dial sqleditor: %s", err))
		}

		sqleditorCli = sqleditor.NewSqlEditorServiceClient(conn)
	})
	return sqleditorCli
}

func CreateOpLog(ctx context.Context, req *sqleditor.CreateOpLogReq) error {
	tilog.Info(ctx, "rpc/sqleditor:CreateOpLog req", zap.Any("req", req))
	startT := time.Now()
	client := getSqleditorClient()

	rsp, err := client.CreateOpLog(ctx, req)
	tc := time.Since(startT)
	tilog.Info(ctx, "rpc/sqleditor:CreateOpLog rsp", zap.Any("cost", tc.String()), zap.Any("rsp", rsp), zap.Any("err", err))
	if err != nil {
		return tierr.NewInternalGRPC("CreateOpLog", err)
	}
	if rsp.BaseResp.ErrCode != 0 {
		return tierr.GetTiErrFromBaseResp(rsp.BaseResp)
	}
	return nil
}
