package grpcli

import (
	"context"

	"github.com/tidbcloud/account/idl/pbgen/proto/acl"
	"github.com/tidbcloud/dataflow-service-ng/pkg/log"
	"github.com/tidbcloud/pkgv2/bizerr"
	"go.uber.org/zap"
)

type AccountAclGrpcClient interface {
	GetClient() acl.AccessServiceClient

	GetDelegateJwtByUser(ctx context.Context, req *acl.GetJwtByUserReq) (*acl.GetJwtByUserResp, bizerr.BizError)

	GetOpenAPIAccess(ctx context.Context, req *acl.GetOpenAPIAccessReq) (*acl.GetOpenAPIAccessResp, bizerr.BizError)
}

type accountAclGrpcClientImpl struct {
	addr   string
	client acl.AccessServiceClient
}

func NewAccountAclGrpcClient(ctx context.Context, addr string) AccountAclGrpcClient {
	logger := log.GetLogger(ctx)
	logger.Info("initializing account-acl client", zap.String("addr", addr))
	conn := MustBuildGrpcClientConnection(ctx, addr)
	accountSvcCli := acl.NewAccessServiceClient(conn)
	return &accountAclGrpcClientImpl{
		addr:   addr,
		client: accountSvcCli,
	}
}

func (c *accountAclGrpcClientImpl) GetClient() acl.AccessServiceClient {
	return c.client
}

func (c *accountAclGrpcClientImpl) GetDelegateJwtByUser(
	ctx context.Context, req *acl.GetJwtByUserReq,
) (*acl.GetJwtByUserResp, bizerr.BizError) {
	resp, err := c.client.GetJwtByUser(ctx, req)
	if err != nil {
		return resp, bizerr.WrapGrpcError(err, "GetJwtByUser")
	}
	if resp.BaseResp.ErrCode != 0 {
		return resp, bizerr.Restore(bizerr.ErrCode(resp.BaseResp.ErrCode), resp.BaseResp.ErrMsg)
	}
	return resp, nil
}

func (c *accountAclGrpcClientImpl) GetOpenAPIAccess(
	ctx context.Context, req *acl.GetOpenAPIAccessReq,
) (*acl.GetOpenAPIAccessResp, bizerr.BizError) {
	resp, err := c.client.GetOpenAPIAccess(ctx, req)
	if err != nil {
		return resp, bizerr.WrapGrpcError(err, "GetOpenAPIAccess")
	}
	return resp, nil
}
