package nodegroup

import (
	"strconv"
	"strings"

	dplanemgrv1 "github.com/tidbcloud/cluster-service-ng/api/dataplane-manager/v1"
)

type NodePoolRole string

const (
	NodePoolRolePrimary  NodePoolRole = "primary"
	NodePoolRoleFallback NodePoolRole = "fallback"
)

func NodePoolMatchesRole(nodePool *dplanemgrv1.NodePool, role NodePoolRole) bool {
	if nodePool == nil {
		return false
	}

	labels := nodePool.GetLabels()
	if !IsManagedByInstanceTypeManager(labels) {
		return role == NodePoolRolePrimary
	}

	if priority, ok := nodePoolPriority(labels); ok {
		isPrimary := priority >= PriorityPrimary
		return (role == NodePoolRolePrimary && isPrimary) || (role == NodePoolRoleFallback && !isPrimary)
	}

	nodePoolName := nodePool.GetName()
	switch {
	case strings.HasPrefix(nodePoolName, string(NodePoolRolePrimary)+"-"):
		return role == NodePoolRolePrimary
	case strings.HasPrefix(nodePoolName, string(NodePoolRoleFallback)+"-"):
		return role == NodePoolRoleFallback
	default:
		return true
	}
}

func nodePoolPriority(labels map[string]string) (uint32, bool) {
	if labels == nil {
		return 0, false
	}
	priorityValue, ok := labels[LabelPriority]
	if !ok || priorityValue == "" {
		return 0, false
	}
	priority, err := strconv.ParseUint(priorityValue, 10, 32)
	if err != nil {
		return 0, false
	}
	return uint32(priority), true
}
