class ApplicationController < ActionController::Base

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

  helper_method :current_user, :logged_in?, :admin?, :reviewer_or_admin?, :contributor_or_above?, :setup_completed?

  private

  def current_user
    @current_user ||= User.find_by(id: session[:user_id]) if session[:user_id]
  end

  def logged_in?
    current_user.present?
  end

  def admin?
    logged_in? && current_user.admin?
  end

  def reviewer_or_admin?
    logged_in? && (current_user.reviewer? || current_user.admin?)
  end

  def contributor_or_above?
    logged_in?
  end

  def require_login
    unless logged_in?
      redirect_to login_path, alert: "You must be logged in to access this page."
    end
  end

  def require_admin
    unless logged_in?
      redirect_to login_path, alert: "You must be logged in to access this page."
      return
    end

    unless current_user.admin?
      redirect_to root_path, alert: "You must be an administrator to access this page."
    end
  end

  def require_reviewer
    unless reviewer_or_admin?
      redirect_to root_path, alert: "You must be a reviewer or administrator to access this page."
    end
  end

  def require_contributor
    unless contributor_or_above?
      redirect_to root_path, alert: "You must be a contributor to access this page."
    end
  end

  def setup_completed?
    SetupState.installed?
  end
end
