package sandstorm

import (
	"time"

	"github.com/aws/aws-sdk-go/aws/client"
	"github.com/aws/aws-sdk-go/aws/credentials"
	"github.com/aws/aws-sdk-go/aws/credentials/stscreds"
	"github.com/aws/aws-sdk-go/service/sts"

	"code.justin.tv/common/config"

	"code.justin.tv/systems/sandstorm/manager"
)

const (
	sandstormTableName = "sandstorm-production"
	sandstormKeyID     = "alias/sandstorm-production"
)

func init() {
	config.Register(map[string]string{
		"sandstorm-role-arn": "arn:aws:iam::734326455073:role/sandstorm/production/templated/role/devtools-development-rockpaperscissors",
	})
}

// Client is a simplified wrapper around sandstorm.
type Client struct {
	manager *manager.Manager
}

// ClientIface is a promised interface for sandstorm Client objects.
//
// This is used for testing.
type ClientIface interface {
	Get(string) (*manager.Secret, error)
}

// New creates a Client with the cross-account AWS role correctly set up.
func New(sess client.ConfigProvider) *Client {
	stsclient := sts.New(sess)
	arp := &stscreds.AssumeRoleProvider{
		ExpiryWindow: 10 * time.Second,
		RoleARN:      config.MustResolve("sandstorm-role-arn"),
		Client:       stsclient,
	}
	creds := credentials.NewCredentials(arp)
	awsConfig := stsclient.Config.Copy().WithCredentials(creds)

	sandstormConfig := manager.Config{
		AWSConfig: awsConfig,
		TableName: sandstormTableName,
		KeyID:     sandstormKeyID,
	}

	return &Client{
		manager: manager.New(sandstormConfig),
	}
}

// Get returns the named secret.
func (c *Client) Get(secretName string) (*manager.Secret, error) {
	return c.manager.Get(secretName)
}
