package utils

import (
	"crypto/md5"
	"fmt"
	"regexp"
)

const (
	externalIdSalt = "infra-api"
)

func getIamIdentity(accountID string, roleName string) string {
	identity := fmt.Sprintf("arn:aws:iam::%s:role/%s", accountID, roleName)
	return identity
}

func GetExternalId(accountID, kubeCluster string) string {
	// Use the `originRoleARN` to calculate the extendid to ensure compatibility
	// as we have imported data using role `serverless-import-${network.Labels[labels.LabelKeyKubernetesCluster]}-v2`.
	// This ensures that the `ExternalID` remains unchanged.
	re := regexp.MustCompile(`-f\d+$`)
	originRoleName := "serverless-import-" + kubeCluster
	originRoleName = re.ReplaceAllString(originRoleName, "-f01")
	originRoleARN := getIamIdentity(accountID, originRoleName)
	h := md5.New()
	h.Write([]byte(originRoleARN)) // #nosec G104
	bs := h.Sum([]byte(externalIdSalt))
	return fmt.Sprintf("%x", bs)
}
