/**
 * Error sanitization utility
 * Removes sensitive information and internal details from error messages
 * before displaying them to users
 */

const INTERNAL_PATTERNS = [
  // File paths and stack traces
  /\/[a-z0-9\-_/\\]+\.(ts|tsx|js|jsx|py|java|cpp|h)/gi,
  /at\s+\w+.*\(.*\)/gi,
  /at Object\.<anonymous>/gi,
  // Database information
  /SQL.*error/gi,
  /database.*error/gi,
  /connection.*pool/gi,
  // Internal server details
  /localhost:\d+/gi,
  /127\.0\.0\.1:\d+/gi,
  /\[.*\].*Error/gi,
  // System paths
  /\/home\/|\/usr\/|\/var\/|\/tmp\//gi,
  // Stack trace markers
  /Stack trace:/gi,
  /Traceback.*most recent call/gi,
];

/**
 * Sanitize error message to remove internal details
 */
export function sanitizeErrorMessage(message: string): string {
  if (!message || typeof message !== 'string') {
    return 'An unexpected error occurred. Please try again.';
  }

  let sanitized = message;

  // Remove internal patterns
  for (const pattern of INTERNAL_PATTERNS) {
    sanitized = sanitized.replace(pattern, '');
  }

  // Remove excessive whitespace
  sanitized = sanitized.replace(/\s+/g, ' ').trim();

  // If message appears to be internal/technical, replace with generic message
  if (
    sanitized.includes('Traceback') ||
    sanitized.includes('at ') ||
    sanitized.includes('.py:') ||
    sanitized.includes('.ts:') ||
    sanitized.includes('.js:')
  ) {
    return 'An unexpected error occurred. Please try again.';
  }

  // Return sanitized message or generic fallback
  return sanitized || 'An unexpected error occurred. Please try again.';
}

/**
 * Extract user-friendly error message from error object
 */
type ApiErrorShape = {
  response?: {
    data?: {
      message?: string;
      detail?: string;
    };
  };
  message?: string;
};

export function getUserFriendlyError(error: unknown): string {
  if (!error) {
    return 'An unexpected error occurred. Please try again.';
  }

  const maybeResponse = (error as ApiErrorShape).response;
  if (maybeResponse?.data?.message) {
    return sanitizeErrorMessage(maybeResponse.data.message);
  }
  if (maybeResponse?.data?.detail) {
    return sanitizeErrorMessage(maybeResponse.data.detail);
  }

  if (error instanceof Error && error.message) {
    return sanitizeErrorMessage(error.message);
  }

  if (typeof error === 'string') {
    return sanitizeErrorMessage(error);
  }

  return 'An unexpected error occurred. Please try again.';
}

/**
 * Check if error message contains internal/technical details
 */
export function isInternalError(message: string): boolean {
  if (!message || typeof message !== 'string') {
    return false;
  }

  return INTERNAL_PATTERNS.some(pattern => pattern.test(message));
}

