module BeefCake
  class PermissionsController < ApplicationController
    before_action :set_permission, only: [:show, :edit, :update, :destroy]

    def index
      authorize Permission

      @permissions = Permission.scoped
      @permissions = @permissions.page(params[:page]).per_page(params[:per_page])
      @permissions = @permissions.all
    end

    def show
    end

    def new
      @permission = Permission.new
      authorize @permission
    end

    def create
      @permission = Permission.new(
        params
          .require(:beef_cake_permission)
          .permit(:name, :description, :canonical_name)
      )
      authorize @permission

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

    def edit
    end

    def update
      @permission.attributes = params
                               .require(:beef_cake_permission)
                               .permit(:name, :description)

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

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

      redirect_back
    end

    protected

    def set_permission
      @permission = Permission.find params[:id]
      authorize @permission

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