module SessionsHelper

  def current_order
    if !session[:order_id].nil?
      Order.find(session[:order_id])
    else
      Order.new
    end
  end

  def paid_order
    session.delete(:order_id)
    current_order = nil
  end

  def log_in(user)
    session[:user_id] = user.id
  end

  def current_user
    current_api_session_token
  end

  def logged_in?
    !!current_user
  end

  def current_user?(user)
    user == current_user
  end

  def current_api_session_token
    @current_api_session_token ||= ApiSessionToken.new(_authorization_header)
  end

  def api_session_token_authenticate!
    return _not_authorized unless _authorization_header && current_api_session_token.valid?
  end

  def _authorization_header
    request.headers['Authorization']
  end

  def _not_authorized message = "Not authorized"
    render json: {error: message}, status: 401
  end
  
  def log_out
    session.delete(:user_id)
    @current_user = nil
  end
end