const sensitiveKeyPattern = /(key|pass|password|secret|token|authorization)/i;

export function maskValue(value: unknown) {
  if (value === null || value === undefined || value === '') {
    return value;
  }
  const text = String(value);
  if (text.length <= 4) {
    return '****';
  }
  return `${text.slice(0, 2)}****${text.slice(-2)}`;
}

export function maskSensitivePayload<T>(payload: T): T {
  if (Array.isArray(payload)) {
    return payload.map((item) => maskSensitivePayload(item)) as T;
  }

  if (!payload || typeof payload !== 'object') {
    return payload;
  }

  return Object.fromEntries(
    Object.entries(payload).map(([key, value]) => [
      key,
      sensitiveKeyPattern.test(key)
        ? maskValue(value)
        : maskSensitivePayload(value),
    ]),
  ) as T;
}
