package util

import (
	"fmt"
	"hash/fnv"
	"strings"

	"github.com/Masterminds/semver"
	"github.com/hashicorp/go-multierror"
)

func TiDBCloudClusterConfigName(orgID string, clusterID string) string {
	return fmt.Sprintf("base--t%s--c%s", orgID, clusterID)
}

func ValidateVersion(ver string) error {
	// semver works for both with/without 'v' prefix, but we want to enforce the prefix in repo
	if !strings.HasPrefix(ver, "v") {
		return fmt.Errorf("version directory %s must be started with 'v'", ver)
	}
	constrain, err := semver.NewConstraint(">= v4.0.9")
	if err != nil {
		return err
	}
	parsed, err := semver.NewVersion(ver)
	if err != nil {
		return err
	}
	_, errs := constrain.Validate(parsed)
	return multierror.Append(nil, errs...).ErrorOrNil()
}

// copied from https://github.com/tidbcloud/config-service/blob/e4d7ca7c8e2e2733b1ad738046c0b7856bcd4f24/gardener/util.go#L48

func TiDBCloudShootName(projectID string, cloudProvider string, region string) string {
	rawName := fmt.Sprintf("%s-%s-%s", projectID, cloudProvider, region)
	return fnvHash(rawName)
}

func fnvHash(raw string) string {
	hash := fnv.New32()
	if _, err := hash.Write([]byte(raw)); err != nil {
		return ""
	}
	return fmt.Sprintf("%x", hash.Sum32())
}
