/**
 * Extracts meaningful error messages from API exceptions and other errors
 * @param err - The error object caught from API calls
 * @returns A user-friendly error message
 */
export function extractErrorMessage(err: unknown): string {
  // Handle ApiException specifically to extract the actual error message
  if (err && typeof err === 'object' && 'isApiException' in err) {
    const apiException = err as any
    try {
      // Try to parse the response as JSON to get the actual error message
      const responseData = JSON.parse(apiException.response)
      return responseData.message || responseData.error || responseData.detail || apiException.message
    } catch {
      // If parsing fails, use the response text directly
      return apiException.response || apiException.message
    }
  } else if (err instanceof Error) {
    return err.message
  }
  
  return 'An unknown error occurred'
}

/**
 * Handles API errors and returns a standardized error object
 * @param err - The error object caught from API calls
 * @returns An object containing the error message and additional context
 */
export function handleApiError(err: unknown): {
  message: string
  isApiException: boolean
  status?: number
  response?: string
} {
  if (err && typeof err === 'object' && 'isApiException' in err) {
    const apiException = err as any
    return {
      message: extractErrorMessage(err),
      isApiException: true,
      status: apiException.status,
      response: apiException.response
    }
  }
  
  return {
    message: extractErrorMessage(err),
    isApiException: false
  }
} 