module Notifications
  class ItemsController < ApplicationController
    before_action :set_item, only: [:edit, :update, :destroy]

    def index
      authorize Item

      @items = Item.scoped
      @items = @items.where(params[:item]) if params[:item].present?
      @items = @items.page(params[:page]).per_page(params[:per_page])
      @items = @items.all
    end

    def new
      @item = Item.new
      authorize @item
    end

    def create
      @item = Item.new item_params
      authorize @item

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

    def edit
    end

    def update
      @item.attributes = item_params

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

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

      redirect_back
    end

    def markdown
      authorize Item
      render plain: Item.markdown(params[:text])
    end

    protected

    def set_item
      @item = Item.find params[:id]

      if @item.errors.present?
        flash[:error] = @item.errors.full_messages.to_sentence
        redirect_to notifications_items_path
      end

      authorize @item
    end

    def item_params
      params.require(:notifications_item).permit(:id, :group_name, :message, :notification_type, :created_at)
    end
  end
end
