# typed: true
class ApplicationController < ActionController::Base
  extend T::Sig
  extend T::Helpers
  include Pundit::Authorization
  include Devise::Controllers::Helpers::ClassMethods

  sig { returns(T.nilable(IpAddressRole)) }
  def current_ip_address_role
    @current_ip_address_role ||= IpAddressRole.for_ip(request.remote_ip)
  end
  helper_method :current_ip_address_role

  sig { returns(T.nilable(T.any(User, IpAddressRole))) }
  def pundit_user
    current_user || current_ip_address_role
  end

  before_action do
    if Rails.env.development? || Rails.env.staging?
      Rack::MiniProfiler.authorize_request
    end
  end

  before_action :authenticate_user!

  # Pundit authorization error handling
  rescue_from Pundit::NotAuthorizedError, with: :user_not_authorized

  protected

  def prometheus_client
    PrometheusExporter::Client.default
  end

  private

  def user_not_authorized
    flash[:alert] = "You are not authorized to perform this action."
    redirect_back(fallback_location: root_path)
  end
end
