module Api module V1 class GamesController < BaseController before_action :set_game, only: [ :show, :update, :destroy ] def index @games = current_user.games.includes(:platform, :genres, :collections) # Filtering @games = @games.by_platform(params[:platform_id]) if params[:platform_id].present? @games = @games.by_genre(params[:genre_id]) if params[:genre_id].present? @games = @games.where(format: params[:format]) if params[:format].present? @games = @games.where(completion_status: params[:completion_status]) if params[:completion_status].present? @games = @games.search(params[:search]) if params[:search].present? # Sorting @games = case params[:sort] when "alphabetical" then @games.alphabetical when "recent" then @games.recent when "rated" then @games.rated else @games.recent end # Pagination page = params[:page] || 1 per_page = params[:per_page] || 25 @games = @games.page(page).per(per_page) render json: @games, include: [ :platform, :genres, :collections ] end def show render json: @game, include: [ :platform, :genres, :collections ] end def create @game = current_user.games.build(game_params) if @game.save render json: @game, status: :created, include: [ :platform, :genres ] else render json: { errors: @game.errors.full_messages }, status: :unprocessable_entity end end def update if @game.update(game_params) render json: @game, include: [ :platform, :genres, :collections ] else render json: { errors: @game.errors.full_messages }, status: :unprocessable_entity end end def destroy @game.destroy head :no_content end def bulk results = { created: [], failed: [] } games_data = params[:games] || [] games_data.each do |game_data| game = current_user.games.build(game_data.permit!) if game.save results[:created] << game else results[:failed] << { data: game_data, errors: game.errors.full_messages } end end render json: { created: results[:created].count, failed: results[:failed].count, details: results }, status: :created end private def set_game @game = current_user.games.find(params[:id]) end def game_params params.require(:game).permit( :title, :platform_id, :format, :date_added, :completion_status, :user_rating, :notes, :condition, :price_paid, :location, :digital_store, :custom_entry, :igdb_id, genre_ids: [] ) end end end end