import crypto from 'crypto';
import { logger } from '../../utils/logger';

/**
 * [BIZ_INF_104] 敏感数据 AES-256 字段级加密 (SecureVaultComponent)
 * @description 核心逻辑：实现基于 AES-256-GCM 的敏感字段级加密。
 * 针对供应商 API Key、用户 PII 等数据进行“静默加密”。
 * 密钥由环境变量 MASTER_ENCRYPTION_KEY 派生，支持 Key Rotation 兼容性预留。
 */
export class SecureVaultComponent {
  private static readonly ALGORITHM = 'aes-256-gcm';
  private static readonly IV_LENGTH = 16;
  private static readonly AUTH_TAG_LENGTH = 16;

  /**
   * 获取主密钥 (32 字节)
   */
  private static getMasterKey(): Buffer {
    const key = process.env.MASTER_ENCRYPTION_KEY || 'default-secret-key-at-least-32-bytes-long';
    return crypto.scryptSync(key, 'salt', 32);
  }

  /**
   * 加密字段
   */
  static encrypt(text: string): string {
    try {
      const iv = crypto.randomBytes(this.IV_LENGTH);
      const key = this.getMasterKey();
      const cipher = crypto.createCipheriv(this.ALGORITHM, key, iv);

      const encrypted = Buffer.concat([cipher.update(text, 'utf8'), cipher.final()]);
      const authTag = cipher.getAuthTag();

      // 返回格式：iv:authTag:encrypted (Base64)
      return Buffer.concat([iv, authTag, encrypted]).toString('base64');
    } catch (err: any) {
      logger.error(`[SecureVault] Encryption failed: ${err.message}`);
      throw new Error('SECURE_VAULT_ENCRYPTION_ERROR');
    }
  }

  /**
   * 解密字段
   */
  static decrypt(encryptedBase64: string): string {
    try {
      const data = Buffer.from(encryptedBase64, 'base64');

      // 分离 iv, authTag, encryptedData
      const iv = data.slice(0, this.IV_LENGTH);
      const authTag = data.slice(this.IV_LENGTH, this.IV_LENGTH + this.AUTH_TAG_LENGTH);
      const encryptedData = data.slice(this.IV_LENGTH + this.AUTH_TAG_LENGTH);

      const key = this.getMasterKey();
      const decipher = crypto.createDecipheriv(this.ALGORITHM, key, iv);
      decipher.setAuthTag(authTag);

      const decrypted = Buffer.concat([decipher.update(encryptedData), decipher.final()]);
      return decrypted.toString('utf8');
    } catch (err: any) {
      logger.error(`[SecureVault] Decryption failed: ${err.message}`);
      throw new Error('SECURE_VAULT_DECRYPTION_ERROR');
    }
  }

  /**
   * 模拟自动脱敏处理 (PII Masking)
   */
  static mask(text: string, type: 'PHONE' | 'EMAIL' | 'KEY' = 'KEY'): string {
    if (!text) return '';
    switch (type) {
      case 'PHONE':
        return text.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
      case 'EMAIL':
        return text.replace(/(.{2}).*(@.*)/, '$1***$2');
      case 'KEY':
        return text.substring(0, 4) + '****' + text.substring(text.length - 4);
      default:
        return '****';
    }
  }
}
