package rorolepicker

import (
	"fmt"
	"hash/fnv"
)

// RolePathPrefix is the iam path prefix for the sharded roles
var RolePathPrefix = "/malachai/auxiliary/sharded/"

// FormatAuxRoleArn formats the services read only role arn from a role name
// and account id
func FormatAuxRoleArn(accountID, roleName string) string {
	return fmt.Sprintf("arn:aws:iam::%s:role/malachai/auxiliary/sharded/%s", accountID, roleName)
}

// PickAuxRole generates the role name for the services table read-only role
// https://docs.google.com/document/d/1h7u81W79oJBvzEM4I1W36KuOcDrZBmlIIiV0PxPFi0w/edit#heading=h.uj4jc4egn191
func PickAuxRole(auxRolePrefix, serviceName string, readOnlyRoleCount int) (string, error) {
	hasher := fnv.New64()
	_, err := hasher.Write([]byte(serviceName))
	if err != nil {
		return "", err
	}
	roleNumber := hasher.Sum64() % uint64(readOnlyRoleCount)
	return fmt.Sprintf("%s-%d", auxRolePrefix, roleNumber), nil
}
