export function redact(obj: any): any {
  if (obj === null || obj === undefined) return obj;
  if (typeof obj === 'string') {
    let str = obj;
    const sensitiveKeys = ['password', 'passwordHash', 'baseSalary', 'bankAccount', 'salary'];
    for (const key of sensitiveKeys) {
      const regex = new RegExp(`("${key}"\\s*:\\s*")[^"]+(")`, 'gi');
      str = str.replace(regex, `$1[REDACTED]$2`);
      const eqRegex = new RegExp(`(${key}\\s*=\\s*)[^\\s&,]+`, 'gi');
      str = str.replace(eqRegex, `$1[REDACTED]`);
    }
    return str;
  }
  if (Array.isArray(obj)) {
    return obj.map(item => redact(item));
  }
  if (typeof obj === 'object') {
    const newObj: any = {};
    const sensitiveKeys = ['password', 'passwordHash', 'baseSalary', 'bankAccount', 'salary'];
    for (const key of Object.keys(obj)) {
      if (sensitiveKeys.includes(key)) {
        newObj[key] = '[REDACTED]';
      } else {
        newObj[key] = redact(obj[key]);
      }
    }
    return newObj;
  }
  return obj;
}

export function setupLogRedaction() {
  if (typeof global !== 'undefined' && !(global as any).__logRedactionSetup) {
    (global as any).__logRedactionSetup = true;

    const originalLog = console.log;
    const originalInfo = console.info;
    const originalWarn = console.warn;
    const originalError = console.error;

    console.log = (...args: any[]) => originalLog(...args.map(redact));
    console.info = (...args: any[]) => originalInfo(...args.map(redact));
    console.warn = (...args: any[]) => originalWarn(...args.map(redact));
    console.error = (...args: any[]) => originalError(...args.map(redact));
  }
}
