# typed: strict
require 'parlour'
class SorbetRails::HelperRbiFormatter
  extend T::Sig
  # @param [Array<Module>] helpers
  # @return [void]
  sig { params(helpers: T::Array[Module]).void }
  def initialize(helpers)
    @parlour = T.let(Parlour::RbiGenerator.new, Parlour::RbiGenerator)
    @helpers = T.let(helpers, T::Array[Module])
  end

  # Generates RBI file's contents.
  # @return [String]
  sig {returns(String)}
  def generate_rbi
    puts "-- Generate sigs for helpers --"

    @parlour.root.add_comment([
      'This is an autogenerated file for Rails helpers.',
      'Please rerun bundle exec rake rails_rbi:helpers to regenerate.'
    ])

    @helpers.each do |helper|
      @parlour.root.create_module(helper.to_s) do |mod|
        mod.create_include('Kernel')
        mod.create_include('ActionView::Helpers')
        ::SorbetRails.config.extra_helper_includes.each do |extra_helper|
          mod.create_include(extra_helper) unless extra_helper == helper.to_s
        end
      end
    end

    if ActionController::Helpers.method_defined?(:helpers)
      # Adds the `helpers` method that provides access to all methods within the
      # application's helpers.
      # https://api.rubyonrails.org/classes/ActionController/Helpers/ClassMethods.html#method-i-helpers
      @parlour.root.create_module('ActionController::Helpers') do |mod|
        mod.create_method(
          'helpers',
          return_type: "T.all(#{@helpers.join(', ')})"
        )
      end
    end

    return @parlour.rbi
  end
end
