class UsersController < ApplicationController
  before_action :authenticate_user!
  after_action :verify_authorized

  def index
    @users = policy_scope User.all
    authorize @users
  end

  def show
    @user ||= User.find(params[:id])
    @micropost = current_user.microposts.build if current_user.signed_in?
    @microposts = @user.microposts.paginate(page: params[:page])
    authorize @user
  end

  def home
    authorize current_user
    @user = current_user
    @micropost = current_user.microposts.build if current_user.signed_in?
    @microposts = @user.microposts.paginate(page: params[:page])
    @feed_items = current_user.feed.paginate(page: params[:page], per_page: 10)
    # authorize @user
    # redirect_to current_user
  end


  def update
    @user = User.find(params[:id])
    authorize @user
    if @user.update_attributes(secure_params)
      redirect_to users_path, notice: 'User updated.'
    else
      redirect_to users_path, alert: 'Unable to update user.'
    end
  end

  def destroy
    user = User.find(params[:id])
    authorize user
    user.destroy
    redirect_to users_path, notice: 'User deleted.'
  end

  private

  def secure_params
    params.require(:user).permit(:role)
  end
end
