package dataapi

import (
	"context"
	"fmt"
	"sync"

	"github.com/tidbcloud/tiinf/errs"
	"go.uber.org/zap"

	"github.com/tidbcloud/account/commons/config"
	"github.com/tidbcloud/dataservices/idl/pbgen/proto/dataapi"
	"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().GrpcConfig.DataAPISvcAddr, tigrpc.WithDefault())
		if err != nil {
			panic(fmt.Sprintf("dial dataapi-svc: %s", err))
		}

		dataAPISvcCli = dataapi.NewDataAPIServiceClient(conn)
	})

	return dataAPISvcCli
}

func ShowDataApp(ctx context.Context, req *dataapi.ShowDataAppReq) (*dataapi.ShowDataAppResp, error) {
	client := getDataAPISvcClient()

	tilog.Info(ctx, "rpc ShowDataApp start", zap.Any("req", req))
	resp, e := client.ShowDataApp(ctx, req)
	tilog.Info(ctx, "rpc ShowDataApp complete", zap.Any("rsp", resp), zap.Any("err", e))
	if e != nil {
		return resp, errs.NewInternalGRPC("ShowDataApp", e)
	}
	if resp.BaseResp.ErrCode != 0 {
		return resp, errs.ParseBaseResp(ctx, resp.BaseResp)
	}
	return resp, nil
}

func ListDataApp(ctx context.Context, req *dataapi.ListDataAppReq) (*dataapi.ListDataAppResp, error) {
	client := getDataAPISvcClient()

	tilog.Info(ctx, "rpc ListDataApp start", zap.Any("req", req))
	resp, e := client.ListDataApp(ctx, req)
	tilog.Info(ctx, "rpc ListDataApp complete", zap.Any("rsp", resp), zap.Any("err", e))
	if e != nil {
		return resp, errs.NewInternalGRPC("ListDataApp", e)
	}
	if resp.BaseResp.ErrCode != 0 {
		return resp, errs.ParseBaseResp(ctx, resp.BaseResp)
	}
	return resp, nil
}
