module BeefCake
  class UsersController < BeefCake::BaseController
    before_action :set_user, only: [:edit, :update, :reactivate]

    def index
      authorize User

      @users = BeefCake::User.all(params)
    end

    def edit
    end

    def reactivate
      if @user.reactivate
        flash[:success] = "Success"
      else
        flash.now[:error] = @user.error.full_messages.to_sentence
      end
      redirect_to edit_beef_cake_user_path(@user)
    end

    def update
      @user.attributes = user_params

      if @user.save
        flash[:success] = "Success"
        redirect_to edit_beef_cake_user_path(@user)
      else
        flash.now[:error] = @user.errors.full_messages.to_sentence
        render :edit
      end
    end

    protected

    def set_user
      @user = User.find params[:id]

      authorize @user
    end

    def user_params
      params.require(:beef_cake_user).permit(role_ids: [])
    end
  end
end
