module BannedWords
  class ItemsController < ApplicationController
    def index
      authorize Item

      @items = BannedWords::Item.scoped
      @items = @items.where(params[:item]) if params[:item]
      @items = @items.all
    end

    def new
      @item = BannedWords::Item.new banned_word_params
      authorize @item
    end

    def create
      @item = BannedWords::Item.new banned_word_params
      authorize @item

      if @item.save
        flash[:success] = "Banned #{@item.word}. This list can take up to a minute to update."
        redirect_to banned_words_items_path
      else
        flash.now[:danger] = "Couldn't ban #{@item.word}."
        render :new
      end
    end

    def destroy
      @item = BannedWords::Item.from_attributes word: params[:id]
      authorize @item

      if @item.destroy
        flash[:success] = "Successfully removed banned word #{params[:id]}. This list can take up to a minute to update."
      else
        flash[:error] = "Unable to remove banned word #{params[:id]}"
      end

      redirect_back
    end

    protected

    def banned_word_params
      return {} if params[:banned_words_item].blank?
      params.require(:banned_words_item).permit(:word, :can_optout)
    end
  end
end
