package encryption

import (
	"bytes"

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

func (c *AuthorizedFieldClient) EncryptString(encCtx authorization.Context, plaintext string) (*authorization.String, error) {
	err := authorization.ValidateContext(encCtx)
	if err != nil {
		return nil, errors.Wrap(err, "invalid authorization context")
	}

	olePayload, err := c.encrypt(encCtx, []byte(plaintext))
	if err != nil {
		return nil, errors.Wrap(err, "could not encrypt authorized field")
	}

	return &authorization.String{
		OlePayload: olePayload,
	}, nil
}

func (c *AuthorizedFieldClient) encrypt(encCtx map[string]string, plaintext []byte) ([]byte, error) {
	var buf bytes.Buffer
	encryptedBuf := c.ole.NewEncryptor(encCtx, &buf)

	_, err := encryptedBuf.Write(plaintext)
	if err != nil {
		return nil, err
	}

	return buf.Bytes(), nil
}
