# frozen_string_literal: true module Api # ProductsController class ProductsController < MasterController def show @product = Product.find_by(public_id: params[:id]) render json: { error_message: 'No existe el producto' }, status: :not_found and return if @product.nil? render json: serialized_object.serializable_hash, status: :ok end def index @products = Product.all render json: serialized_collection.serializable_hash, status: :ok end def create @product = Product.new(permitted_params) if @product.save render json: serialized_object.serializable_hash, status: :ok else render json: @product.errors.full_messages, status: :unprocessable_entity end end def update @product = Product.find_by(public_id: params[:id]) if @product.update(permitted_params) render json: serialized_object.serializable_hash, status: :ok else render json: @product.errors.full_messages, status: :unprocessable_entity end end def destroy @product = Product.find_by(public_id: params[:id]) render json: { error_message: 'No existe el producto' }, status: :not_found and return if @product.nil? @product.destroy render status: :see_other end private def serialized_object Serializers::ProductSerializer(@product).new end def serialized_collection Serializers::ProductSerializer.new(@products.page(params[:page])) end def permitted_params params.permit(:name, :unitary_price, :bulk_price, :picture, :available_quantity, :categories, :company_id) end end end