# frozen_string_literal: true module Api # ProductsController class ProductsController < MasterController def show render status: :not_found and return unless Product.exists?(public_id: params[:id]) render json: serialized_object(params[:id]).serializable_hash, status: :ok end def index @products = Product.all render json: serialized_collection.serializable_hash, status: :ok end def create @product = Product.new(object_params) if @product.save render json: serialized_object(@product.public_id).serializable_hash, status: :ok else render json: { error_messages: @product.errors.full_messages }, status: :unprocessable_entity end end def update @product = Product.find_by(public_id: params[:id]) render status: :not_found and return if @product.nil? if @product.update(object_params) render json: serialized_object(@product.public_id).serializable_hash, status: :ok else render json: { error_messages: @product.errors.full_messages }, status: :unprocessable_entity end end def destroy @product = Product.find_by(public_id: params[:id]) render status: :not_found and return if @product.nil? @product.destroy render status: :see_other end private def scope Product.joins(:company) .select('products.*', 'companies.name as company_name', 'companies.short_name as company_short_name') .includes(picture_attachment: :blob) end def serialized_object(public_id) Serializers::ProductSerializer.new(scope.find_by(public_id:)) end def serialized_collection Serializers::ProductSerializer.new(scope.page(params[:page])) end def permitted_params params.permit(:name, :unitary_price, :bulk_price, :picture, :available_quantity, :categories, :company_id) end def object_params categories = permitted_params[:categories].split(',') public_id = SecureRandom.hex(12) public_id = SecureRandom.hex(12) while Product.exists?(public_id:) permitted_params.merge(categories:, public_id:) end end end