module BeefCake
  class BulkEditController < BeefCake::BaseController
    before_action :set_role
    before_action :set_realms
    before_action :set_realm, only: [:create]

    def index
    end

    def create
      user_ids = params[:user_ids].split
      if params[:batch_action] == 'Add'
        if @role.bulk_add_realm_users(@realm, user_ids)
          flash[:success] = "Added #{user_ids.length} users from #{@realm.name} to #{@role.name}"
        else
          flash[:error] = @role.errors.full_messages.to_sentence
          redirect_back
          return
        end
      elsif params[:batch_action] == 'Remove'
        if @role.bulk_remove_realm_users(@realm, user_ids)
          flash[:success] = "Removed #{user_ids.length} users from #{@realm.name} from #{@role.name}"
        else
          flash[:error] = @role.errors.full_messages.to_sentence
          redirect_back
          return
        end
      end
      redirect_to @role
    end

    protected

    def set_realms
      @realms = Realm.all
    end

    def set_role
      @role = Role.find params[:role_id]
      authorize @role, :bulk_edit?

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

    def set_realm
      @realm = Realm.find(params[:realm_id])
      if @realm.nil?
        flash[:error] = "invalid realm: #{params[:realm_id]}"
        redirect_back
      end
    end

    def redirect_back
      redirect_to beef_cake_role_bulk_edit_index_url
    end
  end
end
