//    \\ SPIKE: Secure your secrets with SPIFFE. — https://spike.ist/
//  \\\\\ Copyright 2024-present SPIKE contributors.
// \\\\\\\ SPDX-License-Identifier: Apache-2.0

package crypto

import (
	"crypto/rand"
	"encoding/hex"

	sdkErrors "github.com/spiffe/spike-sdk-go/errors"
)

var reader = rand.Read

// AES256KeySize defines the size of a key in bytes for AES-256 encryption.
const AES256KeySize = 32

// AES256Seed generates a cryptographically secure random 256-bit key suitable
// for use with AES-256 encryption. The key is returned as a hexadecimal-encoded
// string.
//
// Returns:
//   - string: A 64-character hexadecimal string representing the 256-bit key,
//     empty string on error
//   - *sdkErrors.SDKError: nil on success, or one of the following errors:
//   - ErrCryptoFailedToCreateCipher: if random key generation fails
//
// The function uses a cryptographically secure random number generator to
// ensure the generated key is suitable for cryptographic use. The resulting hex
// string can be decoded back to bytes using hex.DecodeString when needed for
// encryption.
func AES256Seed() (string, *sdkErrors.SDKError) {
	// Generate a 256-bit key
	key := make([]byte, AES256KeySize)

	_, err := reader(key)
	if err != nil {
		failErr := sdkErrors.ErrCryptoFailedToCreateCipher.Wrap(err)
		failErr.Msg = "failed to generate random key"
		return "", failErr
	}

	return hex.EncodeToString(key), nil
}
