import CryptoJS from "crypto-js";

/**
 * AES-128-CBC 加解密工具类
 * 参考中台项目实现，采用类实例模式
 */
class CryptoUtil {
  private key: CryptoJS.lib.WordArray;
  private iv: CryptoJS.lib.WordArray;

  constructor(key: string, iv: string) {
    this.key = CryptoJS.enc.Utf8.parse(key);
    this.iv = CryptoJS.enc.Utf8.parse(iv);
  }

  /**
   * 验证密钥和向量是否有效
   */
  isConfigured(): boolean {
    return Boolean(this.key.sigBytes && this.iv.sigBytes);
  }

  /**
   * 加密：对象/字符串 -> Base64
   */
  encrypt(data: any): string {
    if (data === null || data === undefined) return data;
    try {
      const plainText = typeof data === "object" ? JSON.stringify(data) : String(data);
      const encrypted = CryptoJS.AES.encrypt(plainText, this.key, {
        iv: this.iv,
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.Pkcs7
      });
      return encrypted.toString();
    } catch (error) {
      console.error("Encryption failed:", error);
      throw new Error("请求参数加密失败");
    }
  }

  /**
   * 解解密：Base64 -> 对象/字符串
   */
  decrypt(cipherText: string): any {
    if (!cipherText || typeof cipherText !== "string") return cipherText;
    try {
      const decrypted = CryptoJS.AES.decrypt(cipherText, this.key, {
        iv: this.iv,
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.Pkcs7
      });
      const result = decrypted.toString(CryptoJS.enc.Utf8);
      if (!result) {
        throw new Error("Decryption failed: empty result");
      }
      // 尝试解析为 JSON
      try {
        return JSON.parse(result);
      } catch {
        return result;
      }
    } catch (error) {
      console.error("Decryption failed:", error);
      throw new Error(`响应数据解密失败: ${error instanceof Error ? error.message : String(error)}`);
    }
  }
}

// 获取环境变量
const KEY = import.meta.env.VITE_CRYPTO_KEY || "";
const IV = import.meta.env.VITE_CRYPTO_IV || "";

// 单例导出
export const cryptoUtil = new CryptoUtil(KEY, IV);

/**
 * @deprecated 请使用 cryptoUtil
 */
export const crypto = cryptoUtil;
