package cloudformation

import (
	"context"

	"code.justin.tv/eventbus/client/lowlevel/cfnversion"
	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/aws/credentials"
	"github.com/aws/aws-sdk-go/aws/session"
)

type CredentialFetcher interface {
	AssumeRoleCredentials(accountID string) *credentials.Credentials
}

type Manager struct {
	baseSession       *session.Session
	credentialFetcher CredentialFetcher
}

func NewManager(sess *session.Session, credentialFetcher CredentialFetcher) *Manager {
	return &Manager{
		baseSession:       sess,
		credentialFetcher: credentialFetcher,
	}
}

func (m *Manager) GetVersion(ctx context.Context, awsAccountID string) (string, error) {
	return cfnversion.Get(ctx, m.assumedSession(awsAccountID))
}

func (m *Manager) assumedSession(awsAccountID string) *session.Session {
	creds := m.credentialFetcher.AssumeRoleCredentials(awsAccountID)
	return m.baseSession.Copy(&aws.Config{Credentials: creds})

}
