# typed: strict
module Domain::PaginationHelper
  extend T::Sig
  extend T::Helpers
  include HelpersInterface
  abstract!

  sig do
    params(
      collection: T.untyped,
      link_text: String,
      link_opts: T.untyped,
    ).returns(String)
  end
  def collection_previous_page_link(collection, link_text, link_opts)
    request_url = Addressable::URI.parse(request.url)
    page = collection.current_page - 1
    set_uri_page!(request_url, page)
    path = get_uri_path_and_query(request_url)
    link_to link_text, path, link_opts
  end

  sig do
    params(
      collection: T.untyped,
      link_text: String,
      link_opts: T.untyped,
    ).returns(String)
  end
  def collection_next_page_link(collection, link_text, link_opts)
    request_url = Addressable::URI.parse(request.url)
    page = collection.current_page + 1
    set_uri_page!(request_url, page)
    path = get_uri_path_and_query(request_url)
    link_to link_text, path, link_opts
  end

  sig do
    params(
      collection: T.untyped,
      link_text: String,
      link_opts: T.untyped,
    ).returns(String)
  end
  def collection_previous_page_link(collection, link_text, link_opts)
    request_url = Addressable::URI.parse(request.url)
    page = collection.current_page - 1
    set_uri_page!(request_url, page)
    path = get_uri_path_and_query(request_url)
    link_to link_text, path, link_opts
  end

  sig { params(uri: Addressable::URI, page: T.nilable(Integer)).void }
  def set_uri_page!(uri, page)
    query_values = uri.query_values || {}
    if page.nil? || page <= 1
      query_values.delete("page")
    else
      query_values["page"] = page
    end

    uri.query_values = query_values.empty? ? nil : query_values
  end

  sig { params(uri: Addressable::URI).returns(String) }
  def get_uri_path_and_query(uri)
    path = uri.path
    path += "?#{uri.query}" if uri.query.present?
    path
  end

  sig do
    params(
      params:
        T.any(ActionController::Parameters, T::Hash[T.untyped, T.untyped]),
    ).returns(T.nilable(String))
  end
  def page_str(params)
    if (params[:page] || 1).to_i > 1
      "(page #{params[:page]})"
    else
      nil
    end
  end
end
