package util

import (
	"fmt"
	"strings"

	"github.com/aws/aws-sdk-go-v2/aws/arn"
)

// GetRootUserARN parses the given role ARN and returns the root user ARN.
// If the given ARN is invalid, an empty string is returned.
func GetRootUserARN(roleARN string) string {
	account, err := GetRootUserAccount(roleARN)
	if err != nil {
		return ""
	}
	return fmt.Sprintf("arn:aws:iam::%s:root", account)
}

// GetRootUserAccount returns the account id from the arn
func GetRootUserAccount(arnStr string) (string, error) {
	arn, err := arn.Parse(arnStr)
	if err != nil {
		return "", err
	}
	return arn.AccountID, nil
}

// GetRoleARN returns the role ARN from the given role name and account id
func GetRoleARN(accountID, roleName string) string {
	return fmt.Sprintf("arn:aws:iam::%s:role/%s", accountID, roleName)
}

// GetSANameFromSAEmail returns the service account name from a service account email
// If the given service account email is invalid, an empty string is returned.
func GetSANameFromSAEmail(saEmail string) string {
	fields := strings.Split(saEmail, "@")
	if len(fields) != 2 {
		return ""
	}

	return fields[0]
}
