# typed: true
class RoutesRbiFormatter
  def initialize
    @buffer = []
  end

  def section_title(title)
    @buffer << "\n# Section #{title}"
  end

  def section(routes)
    @buffer << draw_section(routes)
  end

  def header(routes)
  end

  def no_routes(routes, filter)
    @buffer <<
      if routes.none?
        <<~MESSAGE
          You do not have any routes defined!
          Please add some routes in config/routes.rb.
        MESSAGE
      elsif filter.key?(:controller)
        "No routes were found for this controller."
      elsif filter.key?(:grep)
        "No routes were found for this grep pattern."
      end

    @buffer << "For more information about routes, see the Rails guide: https://guides.rubyonrails.org/routing.html."
  end

  def result
    <<~MESSAGE
      # This is an autogenerated file for routes helper methods

      # typed: strong
      class ActionController::Base
        extend T::Sig

      #{@buffer.join("\n").indent(2)}
      end
    MESSAGE
  end

  private
  def draw_section(routes)
    routes.map do |r|
      if r[:name].present?
        <<~MESSAGE
          # Sigs for route #{r[:path]}
          sig { params(args: T.untyped, kwargs: T.untyped).returns(String) }
          def #{r[:name]}_path(*args, **kwargs); end
          sig { params(args: T.untyped, kwargs: T.untyped).returns(String) }
          def #{r[:name]}_url(*args, **kwargs); end
        MESSAGE
      else
        nil
      end
    end.compact
  end
end
