package encryption

import (
	"bytes"
	"io/ioutil"

	"code.justin.tv/eventbus/schema/pkg/eventbus/authorization"
	"github.com/pkg/errors"
)

func (c *AuthorizedFieldClient) DecryptString(blob *authorization.String) (string, error) {
	plaintext, err := c.decrypt(blob.GetOlePayload())
	if err != nil {
		return "", errors.Wrap(err, "could not decrypt authorized field")
	}

	return string(plaintext), nil
}

func (c *AuthorizedFieldClient) decrypt(olePayload []byte) ([]byte, error) {
	if olePayload == nil {
		return nil, ErrNilOLEPayload
	}

	decryptedBuf := c.ole.NewDecryptor(bytes.NewReader(olePayload))
	bs, err := ioutil.ReadAll(decryptedBuf)
	if err != nil {
		return nil, err
	}

	return bs, nil
}
