package cluster

import (
	"fmt"
	"strconv"
	"time"

	"github.com/tidbcloud/shared-provider/pkg/utils/random"
)

const (
	randomLen = 6
	// base to format timestamp
	// 36 = len(0-9) + len(a-z)
	formatBase = 36
)

var (
	timeNow             = time.Now
	timestampStartPoint = time.Date(2022, time.January, 1, 0, 0, 0, 0, time.UTC).Unix()
)

const (
	EndpointTypePublic      = "public"
	EndpointTypePrivate     = "private"
	EndpointTypePrivateLink = "privatelink"
)

// 8 for randomstring and 8 for timestamp
func newDefaultDNSIdentity() string {
	suffix := encodeTimestamp()

	return random.Random(randomLen) + suffix
}

func encodeTimestamp() string {
	n := timeNow().UTC().Unix() - timestampStartPoint
	return strconv.FormatInt(n, formatBase)
}

func (r *reconcileContext) endpointDNS(typ string) string {
	prefix := "tidb"
	switch typ {
	case EndpointTypePublic:
	case EndpointTypePrivate, EndpointTypePrivateLink:
		prefix = typ + "-" + prefix
	default:
		prefix = typ + "-" + prefix
	}
	return fmt.Sprintf("%s.%s.%s", prefix, r.cluster.Spec.SqlEndpoints.DNS.Identity, r.PublicHostedZoneDomain)
}
