package meta

import (
	"context"
	"fmt"

	"github.com/tidbcloud/aws-shared-provider/pkg/gateway/config"
	"github.com/tidbcloud/aws-shared-provider/pkg/infra"
	"github.com/tidbcloud/aws-shared-provider/pkg/utils"
)

// GetClusterOrBranchMeta wraps infra.GetClusterOrBranchMeta to retrieve metadata for a cluster or branch.
func GetClusterOrBranchMeta(
	ctx context.Context,
	regionalInfra infra.RegionalInfra,
	infraApi infra.InfraAPI,
	conf *config.Config,
	token string,
) (*infra.ClusterOrBranchMeta, error) {
	meta, err := infra.GetClusterOrBranchMeta(ctx, regionalInfra, infraApi, token, conf.KubeClusterName)
	if err != nil {
		return nil, err
	}
	if conf.GatewayMode != config.InnerMode && meta.RuMode == "throttled" {
		return nil, utils.NewExternalError(fmt.Sprintf(utils.ERR_CLUSTER_BE_THROTTLED, meta.ClusterID))
	}
	switch conf.GatewayMode {
	case config.PublicMode:
		if !meta.PublicEP {
			return nil, utils.NewExternalError(fmt.Sprintf(utils.ERR_PUBLIC_ENDPOINT_DISABLE, meta.ClusterID))
		}
	case config.PrivatelinkMode:
		if !meta.PrivateEP {
			return nil, utils.NewExternalError(fmt.Sprintf(utils.ERR_PRIVATELINK_ENDPOINT_DISABLE, meta.ClusterID))
		}
	}
	return meta, nil
}
