package authserver

import (
	"context"
	"fmt"
	"sync"

	"github.com/tidbcloud/account/commons/config"
	"github.com/tidbcloud/auth-server/idl/pbgen/proto/provider"
	"github.com/tidbcloud/tiinf/monitor/tilog"
	tigrpc "github.com/tidbcloud/tiinf/transport/tigrpc/client"
	"go.uber.org/zap"
)

func GetIdentityByAccessToken(ctx context.Context, accessToken string) (*provider.GetIdentityByAccessTokenResp, error) {
	client := getAuthServerClient()
	rsp, err := client.GetIdentityByAccessToken(ctx, &provider.GetIdentityByAccessTokenReq{
		RawAccessToken: accessToken,
	})
	tilog.Info(ctx, "GetIdentityByAccessToken result", zap.Any("accessToken", accessToken), zap.Any("rsp", rsp), zap.Any("err", err))
	if err != nil {
		return nil, err
	}
	return rsp, nil
}

var (
	authServerClient     provider.AuthServerServiceClient
	authServerClientOnce sync.Once
)

func getAuthServerClient() provider.AuthServerServiceClient {
	authServerClientOnce.Do(func() {
		ctx := context.Background()
		addr := config.Global().GrpcConfig.AuthServerAddr

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

		authServerClient = provider.NewAuthServerServiceClient(conn)
	})
	return authServerClient
}
