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

/**
 * [BIZ_INF_109] 日志脱敏与 PII 保护 (PII Shield)
 * @description 核心逻辑：在日志输出前对敏感数据进行自动脱敏。
 * 保护客户隐私 (PII) 与供应商密钥。集成 [SecureVaultComponent] 的脱敏算法。
 */
export class LogMaskingService {
  /**
   * 对对象或字符串进行脱敏处理
   */
  static maskData(data: any): any {
    if (typeof data === 'string') {
      return this.maskString(data);
    }

    if (typeof data === 'object' && data !== null) {
      const maskedObj = { ...data };
      for (const key in maskedObj) {
        if (this.isSensitiveKey(key)) {
          maskedObj[key] = SecureVaultComponent.mask(maskedObj[key].toString());
        } else if (typeof maskedObj[key] === 'object') {
          maskedObj[key] = this.maskData(maskedObj[key]);
        }
      }
      return maskedObj;
    }

    return data;
  }

  /**
   * 判断 Key 是否属于敏感字段
   */
  private static isSensitiveKey(key: string): boolean {
    const sensitiveKeys = [
      'password', 'secret', 'key', 'token', 'auth', 
      'phone', 'mobile', 'email', 'address', 'card', 
      'cvv', 'identity', 'pii'
    ];
    const lowerKey = key.toLowerCase();
    return sensitiveKeys.some(sk => lowerKey.includes(sk));
  }

  /**
   * 字符串脱敏
   */
  private static maskString(text: string): string {
    // 简单的正则匹配：邮箱与手机号
    if (text.includes('@')) {
      return SecureVaultComponent.mask(text, 'EMAIL');
    }
    if (/^\d{11}$/.test(text)) {
      return SecureVaultComponent.mask(text, 'PHONE');
    }
    return text;
  }

  /**
   * 安全日志记录 (自动脱敏)
   */
  static info(message: string, data?: any) {
    const maskedData = data ? this.maskData(data) : undefined;
    if (maskedData) {
      logger.info(`${message} ${JSON.stringify(maskedData)}`);
    } else {
      logger.info(message);
    }
  }

  static warn(message: string, data?: any) {
    const maskedData = data ? this.maskData(data) : undefined;
    if (maskedData) {
      logger.warn(`${message} ${JSON.stringify(maskedData)}`);
    } else {
      logger.warn(message);
    }
  }
}
