package namespace

import (
	corev1 "k8s.io/api/core/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"

	cloudv1 "github.com/tidbcloud/infra-api/api/v1"
	"github.com/tidbcloud/shared-provider/pkg/types"
	"github.com/tidbcloud/shared-provider/pkg/utils/labels"
)

const (
	NamespaceKey    = types.KeyPrefix + "owned-namespace"
	NamespacePrefix = "db-"
)

func NewOwnedNamespace(net *cloudv1.Network, ns *corev1.Namespace) *corev1.Namespace {
	if ns == nil {
		return &corev1.Namespace{
			ObjectMeta: metav1.ObjectMeta{
				Name:   GetOwnedNamespaceNameFromNetwork(net),
				Labels: labels.NewOwnerLabels(net, nil),
			},
		}
	}

	ns.Labels = labels.NewOwnerLabels(net, ns.Labels)

	return ns
}

func HasOwnedNamespaceName(net *cloudv1.Network) bool {
	_, ok := net.Annotations[NamespaceKey]
	return ok
}

func GetOwnedNamespaceNameFromNetwork(net *cloudv1.Network) string {
	ns, ok := net.Annotations[NamespaceKey]
	if !ok {
		return NamespacePrefix + net.Namespace
	}

	return ns
}

func SetOwnedNamespaceNameInNetwork(net *cloudv1.Network, ns string) {
	if net.Annotations == nil {
		net.Annotations = map[string]string{}
	}

	net.Annotations[NamespaceKey] = ns
}
