package e2eutil

import (
	"context"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/aws/session"
	"github.com/aws/aws-sdk-go/service/kms"
	"go.uber.org/multierr"

	kmsmanager "code.justin.tv/eventbus/controlplane/internal/clients/kms"
	"code.justin.tv/eventbus/controlplane/internal/e2eaccounts"
)

func KMSGrants(keyARN string) ([]*kms.GrantListEntry, error) {
	sess := session.Must(session.NewSession(e2eaccounts.AccountCredentials().MainConfig()))
	manager := kmsmanager.NewManager(sess, keyARN)
	return manager.AllGrants(context.Background())

}

func KMSRevokeGrants(keyARN string, grants []*kms.GrantListEntry) error {
	sess := session.Must(session.NewSession(e2eaccounts.AccountCredentials().MainConfig()))
	manager := kmsmanager.NewManager(sess, keyARN)
	var multiErr error
	for _, grant := range grants {
		err := manager.Revoke(context.Background(), aws.StringValue(grant.GrantId))
		multiErr = multierr.Append(multiErr, err)
	}
	return multiErr
}
