package com.yushu.common.utils;

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;
import java.util.Base64;

/**
 * AES加密工具类
 * 用于敏感数据（如API Key）的加密存储
 * 
 * @author yushu
 */
public class AesUtils {
    
    private static final Logger log = LoggerFactory.getLogger(AesUtils.class);
    
    // 密钥（16位）- 生产环境应从配置文件读取
    private static final String SECRET_KEY = "YuShuAiKey2024!@";
    
    // 初始向量（16位）
    private static final String IV = "YuShuInitVector!";
    
    private static final String ALGORITHM = "AES/CBC/PKCS5Padding";

    /**
     * AES加密
     * 
     * @param plainText 明文
     * @return Base64编码的密文
     */
    public static String encrypt(String plainText) {
        if (plainText == null || plainText.isEmpty()) {
            return plainText;
        }
        try {
            SecretKeySpec keySpec = new SecretKeySpec(SECRET_KEY.getBytes(StandardCharsets.UTF_8), "AES");
            IvParameterSpec ivSpec = new IvParameterSpec(IV.getBytes(StandardCharsets.UTF_8));
            
            Cipher cipher = Cipher.getInstance(ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);
            
            byte[] encrypted = cipher.doFinal(plainText.getBytes(StandardCharsets.UTF_8));
            return Base64.getEncoder().encodeToString(encrypted);
        } catch (Exception e) {
            log.error("AES加密失败", e);
            return plainText;
        }
    }

    /**
     * AES解密
     * 
     * @param encryptedText Base64编码的密文
     * @return 明文
     */
    public static String decrypt(String encryptedText) {
        if (encryptedText == null || encryptedText.isEmpty()) {
            return encryptedText;
        }
        try {
            SecretKeySpec keySpec = new SecretKeySpec(SECRET_KEY.getBytes(StandardCharsets.UTF_8), "AES");
            IvParameterSpec ivSpec = new IvParameterSpec(IV.getBytes(StandardCharsets.UTF_8));
            
            Cipher cipher = Cipher.getInstance(ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
            
            byte[] decrypted = cipher.doFinal(Base64.getDecoder().decode(encryptedText));
            return new String(decrypted, StandardCharsets.UTF_8);
        } catch (Exception e) {
            // 如果解密失败，可能是未加密的旧数据，直接返回原值
            log.warn("AES解密失败，可能是未加密数据: {}", e.getMessage());
            return encryptedText;
        }
    }

    /**
     * 判断是否是加密后的数据（Base64格式）
     */
    public static boolean isEncrypted(String text) {
        if (text == null || text.isEmpty()) {
            return false;
        }
        try {
            Base64.getDecoder().decode(text);
            // 如果能解码且长度是16的倍数（AES块大小），可能是加密数据
            return text.length() % 4 == 0 && text.length() >= 24;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 脱敏显示API Key
     * 
     * @param apiKey 原始API Key
     * @return 脱敏后的显示值，如 sk-ab****ef
     */
    public static String mask(String apiKey) {
        if (apiKey == null || apiKey.length() <= 8) {
            return "****";
        }
        return apiKey.substring(0, 4) + "****" + apiKey.substring(apiKey.length() - 4);
    }
}
