module Games
  class AddBoxartsController < Games::BaseController
    before_action :set_add_boxart, only: [:show, :update]

    def index
      authorize AddBoxart
      if params[:name].present?
        @add_boxart = AddBoxart.find(params[:name])

        return redirect_to(games_add_boxart_path(@add_boxart)) if @add_boxart.persisted?

        flash.now[:error] = @add_boxart.errors.full_messages.to_sentence
      end
    end

    def show
    end

    def update
      @add_boxart.attributes = add_boxart_params
      if !@add_boxart.save
        flash.now[:error] = @add_boxart.errors.full_messages.to_sentence
        render :show
      else
        flash[:success] = "Successfully updated boxart for #{@add_boxart.name}."
        redirect_to @add_boxart
      end
    end

    protected

    def set_add_boxart
      @add_boxart = AddBoxart.find params[:id]
      unless @add_boxart.persisted?
        flash[:error] = @add_boxart.errors.full_messages.to_sentence
        redirect_to games_add_boxarts_path
      end
      authorize @add_boxart
    end

    def add_boxart_params
      return {} if params[:games_add_boxart].blank?
      params.require(:games_add_boxart).permit(:name, :image, :discovery_art)
    end
  end
end
