package shop.alien.util.encryption;

import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;

/**
 * 标准 AES 加解密工具类
 * 模式：AES/CBC/PKCS5Padding
 * 编码：UTF-8
 */
public class StandardAesUtil {

    private static final Logger log = LoggerFactory.getLogger(StandardAesUtil.class);
    private static final String ALGORITHM = "AES/CBC/PKCS5Padding";

    public static String encrypt(String data, String key, String iv) {
        try {
            Cipher cipher = Cipher.getInstance(ALGORITHM);
            SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "AES");
            IvParameterSpec ivSpec = new IvParameterSpec(iv.getBytes(StandardCharsets.UTF_8));
            
            cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);
            byte[] encrypted = cipher.doFinal(data.getBytes(StandardCharsets.UTF_8));
            return Base64.encodeBase64String(encrypted);
        } catch (Exception e) {
            log.error("AES加密失败: {}", e.getMessage());
            return null;
        }
    }

    public static String decrypt(String base64Data, String key, String iv) {
        try {
            if (base64Data == null || base64Data.isEmpty()) {
                return null;
            }
            log.debug("AES解密尝试: data_len={}, key_len={}, iv_len={}", base64Data.length(), key == null ? 0 : key.length(), iv == null ? 0 : iv.length());
            
            Cipher cipher = Cipher.getInstance(ALGORITHM);
            SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "AES");
            IvParameterSpec ivSpec = new IvParameterSpec(iv.getBytes(StandardCharsets.UTF_8));
            
            cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
            byte[] decoded = Base64.decodeBase64(base64Data);
            byte[] original = cipher.doFinal(decoded);
            return new String(original, StandardCharsets.UTF_8);
        } catch (Exception e) {
            log.error("AES解密失败: data_preview={}, error={}", 
                      base64Data.substring(0, Math.min(base64Data.length(), 20)), e.getMessage());
            return null;
        }
    }
}
