package utils

import (
	"strconv"
	"strings"

	cloudv1 "github.com/tidbcloud/infra-api/api/v1"
	"github.com/tidbcloud/infra-provider/pkg/consts"
	"github.com/tidbcloud/infra-provider/pkg/util"
)

const AWSLoadBalancerIPAddressTypeAnnotation = "service.beta.kubernetes.io/aws-load-balancer-ip-address-type"

// NLBSourceRanges returns the ingress source ranges required by the NLB
// address family. AWS Load Balancer Controller uses these ranges to build the
// managed frontend security group rules.
func NLBSourceRanges(addressType cloudv1.PrivateLinkIPAddressType) []string {
	ranges := []string{"0.0.0.0/0"}
	if addressType == cloudv1.PrivateLinkIPAddressTypeDualstack {
		ranges = append(ranges, "::/0")
	}
	return ranges
}

func SetNLBAnnoForTiproxy(annotation map[string]string, tlsEnabled, useTiProxyAsLBTarget bool) {
	// Deprecated, see https://kubernetes-sigs.github.io/aws-load-balancer-controller/v2.6/guide/service/annotations/#resource-attributes
	// Use "service.beta.kubernetes.io/aws-load-balancer-attributes" = "load_balancing.cross_zone.enabled=true" instead
	annotation["service.beta.kubernetes.io/aws-load-balancer-cross-zone-load-balancing-enabled"] = "true"
	annotation["service.beta.kubernetes.io/aws-load-balancer-attributes"] = "load_balancing.cross_zone.enabled=true"

	if !useTiProxyAsLBTarget {
		delete(annotation, "service.beta.kubernetes.io/aws-load-balancer-healthcheck-protocol")
		delete(annotation, "service.beta.kubernetes.io/aws-load-balancer-healthcheck-port")
		delete(annotation, "service.beta.kubernetes.io/aws-load-balancer-healthcheck-path")
	} else {
		// seems that when executing full_service task, `t.TidbCluster` may be nil
		if tlsEnabled {
			annotation["service.beta.kubernetes.io/aws-load-balancer-healthcheck-protocol"] = "https"
		} else {
			annotation["service.beta.kubernetes.io/aws-load-balancer-healthcheck-protocol"] = "http"
		}
		annotation["service.beta.kubernetes.io/aws-load-balancer-healthcheck-port"] = strconv.Itoa(util.TiProxyStatusTargetPort)
		annotation["service.beta.kubernetes.io/aws-load-balancer-healthcheck-path"] = util.TiProxyStatusHealthPath
	}
}

// SetNLBAnnoToEnablePPV2 Annotate NLB to Enable PPv2
func SetNLBAnnoToEnablePPV2(c *cloudv1.Cluster, annotations map[string]string) {
	// FRM-2728: https://tidb.atlassian.net/browse/FRM-2728
	if c.FeatureEnabled(consts.ClusterFeatureUsePPv2PrivateNLB) {
		annotations["service.beta.kubernetes.io/aws-load-balancer-target-group-attributes"] = strings.Join([]string{
			"preserve_client_ip.enabled=false",
			"proxy_protocol_v2.enabled=true",
			// About header_replacement, see the design: https://pingcap.feishu.cn/wiki/SI9EwimDXijOH6k4bhrcb45VnSb#share-ZhQOdUdrEogldVxl5tTcHDU0nrf
			// This attribute can be set only after contacting AWS Support
			// to have it authorized at the REGION scope.
			"proxy_protocol_v2.client_to_server.header_placement=on_first_ack",
		}, ",")
	}
}
