package encryption

import (
	"time"

	"github.com/aws/aws-sdk-go/aws/client"
	"github.com/aws/aws-sdk-go/service/kms"
	"github.com/pkg/errors"

	"code.justin.tv/amzn/TwitchOLE/ole"
	"code.justin.tv/amzn/TwitchOLE/ole/oleiface"
)

type AuthorizedFieldClient struct {
	ole oleiface.OleAPI
}

type authorizedFieldClientConfig struct {
	ole *ole.KMSOleClientConfig
}

type AuthorizedFieldClientOption func(*authorizedFieldClientConfig)

// NewAuthorizedFieldClient creates a wrapper around an OLE client for use in encrypting and decrypting
// authorized fields of EventBus events.
func NewAuthorizedFieldClient(sess client.ConfigProvider, opts ...AuthorizedFieldClientOption) (*AuthorizedFieldClient, error) {
	cfg := defaultOLEConfig()
	for _, option := range opts {
		option(cfg)
	}

	kmsClient := kms.New(sess)
	c, err := ole.NewKMSOleClient(kmsClient, *cfg.ole)
	if err != nil {
		return nil, errors.Wrap(err, "could not initialize OLE client")
	}

	return &AuthorizedFieldClient{
		ole: c,
	}, nil
}

// WithCMKArn allows for overriding the default CMK used to perform cryptographic operations
// against. It is not recommended that this option is used unless you know what you are doing!
func WithCMKArn(arn string) AuthorizedFieldClientOption {
	return func(cfg *authorizedFieldClientConfig) {
		cfg.ole.CMKArn = arn
	}
}

// WithDataKeyTTLSplay configures the random time added to the data encryption key TTL. The TTL
// for data encryption keys is 10 minutes.
func WithDataKeyTTLSplay(splay time.Duration) AuthorizedFieldClientOption {
	return func(cfg *authorizedFieldClientConfig) {
		cfg.ole.DataKeyTTLSplay = splay
	}
}

func defaultOLEConfig() *authorizedFieldClientConfig {
	return &authorizedFieldClientConfig{
		ole: &ole.KMSOleClientConfig{
			CMKArn:                DefaultCMKArn,
			DataKeyTTL:            DefaultDataKeyTTL,
			DataKeyTTLSplay:       DefaultDataKeyTTLSplay,
			EncryptionKeyMaxUsage: DefaultEncryptionKeyMaxUsage,
			MaxCacheSize:          DefaultMaxCacheSize,
		},
	}
}
