class ApplicationController < ActionController::Base
  before_action :set_current_request_details
  before_action :authenticate_user!
  before_action :verified_user!

  verify_authorized

  private
    def current_user
      Current.user || authenticate_user_from_session
    end
    helper_method :current_user

    def authenticate_user_from_session
      session_record = Session.find_by_id(cookies.signed[:session_token])
      Current.session = session_record
      Current.user
    end

    def user_signed_in?
      current_user.present?
    end
    helper_method :user_signed_in?

    def authenticate_user!
      unless user_signed_in?
        redirect_to sign_in_path
      end
    end

    def verified_user!
      if user_signed_in?
        unless current_user.verified?
          flash[:alert] = "Verify your email!"
          redirect_to profile_path
        end
      end
    end

    def set_current_request_details
      Current.user_agent = request.user_agent
      Current.ip_address = request.ip
    end
end
