package randstr

import (
	"fmt"
	"regexp"
	"strconv"
	"time"
)

const (
	dnsSegmentLen = 6
	// 36 = len(0-9) + len(a-z)
	dnsSegmentBase = 36
)

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

// dnsIdentityRegex matches the format produced by GenDnsIdentity:
// 6 lowercase letters followed by one or more base-36 characters (lowercase letters or digits).
var dnsIdentityRegex = regexp.MustCompile(`^[a-z]{6}[a-z0-9]+$`)

func GenDnsIdentity() string {
	n := time.Now().UTC().Unix() - timestampStartPoint.Unix()
	s := strconv.FormatInt(n, dnsSegmentBase)

	return fmt.Sprintf("%s%s", GenWithCharset(dnsSegmentLen, LowercaseAlphabetCharset), s)
}

// ValidateDnsIdentity checks whether the given string matches the format
// produced by GenDnsIdentity: 6 lowercase letters followed by a base-36
// encoded timestamp (lowercase letters and digits).
func ValidateDnsIdentity(identity string) bool {
	return dnsIdentityRegex.MatchString(identity)
}
