# typed: strict
module Domain::ModelHelper
  extend T::Sig
  extend T::Helpers
  include HelpersInterface
  include Pundit::Authorization
  abstract!

  sig do
    params(
      model: HasViewPrefix,
      partial: String,
      as: Symbol,
      expires_in: ActiveSupport::Duration,
    ).returns(T.nilable(String))
  end
  def render_for_model(model, partial, as:, expires_in: 1.hour)
    cache_key = [model, policy(model), partial].compact
    Rails
      .cache
      .fetch(cache_key, expires_in:) do
        prefixes = lookup_context.prefixes
        partial_path =
          prefixes
            .map { |prefix| "#{prefix}/#{model.class.view_prefix}/_#{partial}" }
            .find { |view| lookup_context.exists?(view) } ||
            prefixes
              .map { |prefix| "#{prefix}/default/_#{partial}" }
              .find { |view| lookup_context.exists?(view) } ||
            Kernel.raise("no partial found for #{partial} in #{prefixes}")

        partial_path = partial_path.split("/")
        T.must(partial_path.last).delete_prefix!("_")
        partial_path = partial_path.join("/")
        render partial: partial_path, locals: { as => model }
      end
  end
end
