package config

import (
	"entrance-grpc/iam"
	"github.com/sirupsen/logrus"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
	"google.golang.org/grpc/keepalive"
	"os"
	"time"
)

var iamClient iam.IamClient
var conn *grpc.ClientConn

func InitEntranceIamClient() {
	if os.Getenv("ADMIN_GRPC_SERVER") == "" {
		logrus.Warnf("ADMIN_GRPC_SERVER is empty")
		return
	}
	var err error
	conn, err = grpc.NewClient(os.Getenv("ADMIN_GRPC_SERVER"),
		grpc.WithTransportCredentials(insecure.NewCredentials()),
		grpc.WithKeepaliveParams(keepalive.ClientParameters{
			Time:                30 * time.Second, // 发送 ping 的间隔
			Timeout:             10 * time.Second, // 等待 ack 的超时
			PermitWithoutStream: true,             // 即使没有活跃流也发送 ping
		}),
	)

	if err != nil {
		logrus.Warnf("did not connect: %v", err)
	}

	iamClient = iam.NewIamClient(conn)
}

func GetIamClient() iam.IamClient {
	if iamClient == nil {
		InitEntranceIamClient()
	}
	return iamClient
}

func CloseGrpcConn() {
	conn.Close()
}
