class ApplicationController < ActionController::Base
  include Authentication
  # Only allow modern browsers supporting webp images, web push, badges, import maps, CSS nesting, and CSS :has.
  allow_browser versions: :modern

  # Changes to the importmap will invalidate the etag for HTML responses
  stale_when_importmap_changes

  include Pagy::Backend
  include Pagy::Frontend
  include Pundit::Authorization

  helper_method :current_user, :user_signed_in?, :current_user_admin?, :current_user_viewer?

  rescue_from Pundit::NotAuthorizedError, with: :user_not_authorized

  private

  def current_user
    Current.session&.user
  end

  def user_signed_in?
    current_user.present?
  end

  def current_user_admin?
    current_user&.admin?
  end

  def current_user_viewer?
    current_user&.viewer?
  end

  def require_admin
    unless current_user_admin?
      redirect_to root_path, alert: "Admin access required"
    end
  end

  def require_write_access
    if current_user_viewer?
      redirect_to root_path, alert: "Viewer access - cannot make changes"
    end
  end

  def after_authentication_url
    session.delete(:return_to_after_authenticating) || root_url
  end

  def user_not_authorized
    if user_signed_in?
      redirect_to root_path, alert: "You don't have permission to perform this action."
    else
      redirect_to new_session_path, alert: "Please sign in to continue."
    end
  end
end
