package crypto

import (
	"crypto/aes"
	"crypto/cipher"
	"crypto/rand"
	"encoding/base64"
	"encoding/hex"
	"errors"
	"io"
)

// TianyuanEncrypt 天远数据AES-128-CBC加密，返回Base64编码的字符串
// 与Node.js中的aesEncrypt函数对应
func TianyuanEncrypt(plainText []byte, keyHex string) (string, error) {
	// 将16进制密钥转换为字节
	keyBuffer, err := hex.DecodeString(keyHex)
	if err != nil {
		return "", err
	}

	// 创建AES密码器
	block, err := aes.NewCipher(keyBuffer)
	if err != nil {
		return "", err
	}

	blockSize := block.BlockSize() // AES块大小为16字节

	// 生成随机IV
	iv := make([]byte, blockSize)
	if _, err := io.ReadFull(rand.Reader, iv); err != nil {
		return "", err
	}

	// 创建CBC加密器
	mode := cipher.NewCBCEncrypter(block, iv)

	// PKCS7填充
	paddedText := PKCS7Padding(plainText, blockSize)

	// 加密
	encrypted := make([]byte, len(paddedText))
	mode.CryptBlocks(encrypted, paddedText)

	// 将IV和加密数据连接在一起，然后Base64编码
	result := append(iv, encrypted...)
	return base64.StdEncoding.EncodeToString(result), nil
}

// TianyuanDecrypt 天远数据AES-128-CBC解密，返回解密后的字节数组
// 与Node.js中的aesDecrypt函数对应
func TianyuanDecrypt(encryptedText, keyHex string) ([]byte, error) {
	// 将16进制密钥转换为字节
	keyBuffer, err := hex.DecodeString(keyHex)
	if err != nil {
		return nil, err
	}

	// Base64解码
	encryptedBuffer, err := base64.StdEncoding.DecodeString(encryptedText)
	if err != nil {
		return nil, err
	}

	// 创建AES密码器
	block, err := aes.NewCipher(keyBuffer)
	if err != nil {
		return nil, err
	}

	blockSize := block.BlockSize()

	// 检查数据长度
	if len(encryptedBuffer) < blockSize {
		return nil, errors.New("encrypted text too short")
	}

	// 提取IV和加密数据
	iv := encryptedBuffer[:blockSize]
	encryptedData := encryptedBuffer[blockSize:]

	// 检查加密数据长度是否为块大小的倍数
	if len(encryptedData)%blockSize != 0 {
		return nil, errors.New("encrypted data is not a multiple of the block size")
	}

	// 创建CBC解密器
	mode := cipher.NewCBCDecrypter(block, iv)

	// 解密
	decrypted := make([]byte, len(encryptedData))
	mode.CryptBlocks(decrypted, encryptedData)

	// 去除PKCS7填充
	result, err := PKCS7UnPadding(decrypted)
	if err != nil {
		return nil, err
	}

	return result, nil
}
