export class ApiError extends Error {
  constructor(message) {
    super(message)
    this.name = 'ApiError'
  }
}

export function normalizeApiError(error_) {
  if (!error_?.response && !error_?.request) {
    return error_
  }

  const error = error_.response
    ? new ApiError(`Response error: ${error_?.response?.statusText}`)
    : new ApiError(`Network error: ${error_?.message}`)

  error.statusCode =
    !error_.response && error_.code === 'ECONNABORTED'
      ? 408
      : !error_.response && !error.isTimeoutError
      ? 599
      : error_?.response?.status || 500

  error.errorType = 'api'
  error.url = (error_?.config?.baseURL || '') + (error_?.config?.url || '')
  error.headers = error_?.config?.headers
  error.data = error_?.config?.data
  error.timeout = error_?.config?.timeout

  if (error.url) {
    try {
      const parsedUrl = new URL(error.url)
      error.hostname = parsedUrl.hostname
      error.pathname = parsedUrl.pathname
      error.search = parsedUrl.search
    } catch {}
  }

  return error
}
