package sigutils

import (
	"crypto/sha256"
	"encoding/base64"
	"io"
)

// EmptyBodyHash is a base64-encoded sha256sum of empty byte slice
var EmptyBodyHash = []byte(`47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU=`)

// GenerateHashedBody hashes a request body
func GenerateHashedBody(body io.Reader) (hash []byte, err error) {
	if body == nil {
		hash = EmptyBodyHash
		return
	}

	hasher := sha256.New()
	_, err = io.Copy(hasher, body)
	if err != nil {
		return
	}
	hashedBody := hasher.Sum(nil)
	hash = make([]byte, base64.StdEncoding.EncodedLen(len(hashedBody)))
	base64.StdEncoding.Encode(hash, hasher.Sum(nil))
	return
}
