/**
 * Redact PII from error strings before returning to admin clients.
 * DB writes and internal logs use raw values; this is the client-response barrier.
 */

const EMAIL_PATTERN = /[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g;
/** 7+ consecutive digits, or 7+ digits with -, space, ., () separators between them. */
const PHONE_LIKE_PATTERN = /(?:\d[\s.\-()]*){6,}\d|\d{7,}/g;
const LAST_ERROR_MAX_LEN = 300;

export function redactErrorForClient(error: string | null): string | null {
  if (error == null) return null;
  let s = error.replace(EMAIL_PATTERN, '[email]').replace(PHONE_LIKE_PATTERN, '[redacted]');
  if (s.length > LAST_ERROR_MAX_LEN) {
    s = `${s.slice(0, LAST_ERROR_MAX_LEN)}…`;
  }
  return s;
}
