#' Generate base request
#'
#' This function takes a url and creates a basic httr2 request that
#' adds the user-agent and adds an authorization token to the
#' `X-Esri-Authorization` header.
#'
#' @param url a valid url that is passed to [`httr2::request()`]
#' @param token an object of class `httr2_token` as generated by [`auth_code()`]
#'  or related function
#' @param path a character vector of paths to be appended to url using [`httr2::req_url_path_append()`]
#' @param query a named vector or named list of query parameters to be appended to the url using [`httr2::req_url_query()`]
#' @param error_call the caller environment to be used when propagating errors.
#' @export
#' @examples
#' arc_base_req("https://arcgis.com")
#' @returns an `httr2_request` with the `X-Esri-Authorization` header and `User-Agent` set.
arc_base_req <- function(
  url,
  token = NULL,
  path = NULL,
  query = NULL,
  error_call = rlang::caller_env()
) {
  # set the user agent
  req <- arc_agent(httr2::request(url))

  # handle path if provided
  if (!is.null(path)) {
    # check path is a character vector
    if (!rlang::is_bare_character(path)) {
      cli::cli_abort(
        "{.arg path} must be a character vector",
        call = error_call
      )
    }

    # add path to the url
    req <- httr2::req_url_path_append(
      req,
      rlang::inject(!!path)
    )
  }

  # append a query as well
  if (!is.null(query)) {
    if (!rlang::is_named2(query)) {
      cli::cli_abort(
        "{.arg query} must be a named list",
        call = error_call
      )
    }

    req <- httr2::req_url_query(req, !!!query)
  }

  # if token is not missing, check it
  if (!is.null(token)) {
    # ensure that the token is an httr2_token
    # token <- validate_or_refresh_token(token, error_call)

    # set the auth header
    req <- httr2::req_headers(
      req,
      "X-Esri-Authorization" = paste("Bearer", token[["access_token"]])
    )
  }

  req
}
