module BeefCake
  class RolesController < BeefCake::BaseController
    before_action :set_role, only: [:show, :edit, :update, :destroy, :remove_user]

    def index
      authorize Role

      @roles = Role.scoped
      @roles = @roles.page(params[:page]).per_page(params[:per_page])
      @roles = @roles.all
    end

    def show
    end

    def new
      @role = Role.new
      authorize @role
    end

    def create
      @role = Role.new role_params
      authorize @role

      if @role.save
        flash[:success] = "Success"
        redirect_to beef_cake_roles_path
      else
        flash.now[:danger] = @role.errors.full_messages.to_sentence
        render :new
      end
    end

    def edit
    end

    def update
      @role.attributes = role_params

      if @role.save
        flash[:success] = "Success"
        redirect_to beef_cake_roles_path
      else
        flash.now[:danger] = @role.errors.full_messages.to_sentence
        render :edit
      end
    end

    def destroy
      if @role.destroy
        flash[:success] = "Success"
      else
        flash[:error] = @role.errors.full_messages.to_sentence
      end

      redirect_back
    end

    def remove_user
      if @role.remove_user(params[:user_id])
        flash[:success] = "Success"
      else
        flash[:error] = @role.errors.full_messages.to_sentence
      end
      redirect_to beef_cake_role_path(@role)
    end

    protected

    def set_role
      @role = Role.find params[:id] || params[:role_id]
      authorize @role

      unless @role.persisted?
        flash[:error] = @role.errors.full_messages.to_sentence
        redirect_to beef_cake_roles_path
      end
    end

    def role_params
      params.require(:beef_cake_role).permit!
    end
  end
end
