module Boxart
  class GamesController < Boxart::BaseController
    before_action :set_game, only: [:show, :update]

    def index
      authorize Game

      if params[:name].present?
        @game = Game.find(params[:name])

        return redirect_to(boxart_game_path(@game)) if @game.persisted?

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

    def show
    end

    def update
      @game.attributes = game_params

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

    protected

    def set_game
      @game = Game.find(params[:id])

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

      authorize @game
    end

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