package devops

import (
	"context"
	"fmt"
	"sync"

	"github.com/tidbcloud/account/commons/config"
	auth "github.com/tidbcloud/devops/idl/proto/devops_server/auth/v1"
	"github.com/tidbcloud/tiinf/errs"
	"github.com/tidbcloud/tiinf/monitor/tilog"
	tigrpc "github.com/tidbcloud/tiinf/transport/tigrpc/client"
	"go.uber.org/zap"
)

var (
	devopsCli     auth.AuthServiceClient
	devopsSvcOnce sync.Once
)

type DevopsAPIHandlerImpl struct{}

func getAuthSvcClient() auth.AuthServiceClient {
	devopsSvcOnce.Do(func() {
		ctx := context.Background()
		addr := config.Global().GrpcConfig.DevopsSvcAddr

		conn, err := tigrpc.NewClientConn(addr, tigrpc.WithDefault())
		tilog.Info(ctx, "Initializing account service client", zap.Any("err", err), zap.String("addr", addr))
		if err != nil {
			panic(fmt.Sprintf("dial account-svc: %s", err))
		}

		devopsCli = auth.NewAuthServiceClient(conn)
	})
	return devopsCli
}

func (h *DevopsAPIHandlerImpl) HasAccess(ctx context.Context, in *auth.HasAccessReq) (*auth.HasAccessResp, error) {
	resp, err := getAuthSvcClient().HasAccess(ctx, in)
	if err != nil {
		return nil, errs.NewInternalGRPC("HasAccess", err)
	}
	return resp, nil
}

func (h *DevopsAPIHandlerImpl) GetUser(ctx context.Context, in *auth.GetUserReq) (*auth.GetUserResp, error) {
	resp, err := getAuthSvcClient().GetUser(ctx, in)
	if err != nil {
		return nil, errs.NewInternalGRPC("GetUser", err)
	}
	return resp, nil
}
