# frozen_string_literal: true module Api # AddressesController class AddressesController < AuthenticatedController def index @addresses = current_user_account.addresses render json: serialized_collection.serializable_hash, status: :ok end def create @service = Services::CreateAddressService.new(current_user_account, service_params) begin unless @service.call render json: { error_messages: @service.address.errors.full_messages }, status: :unprocessable_entity return end rescue ActiveRecord::RecordNotUnique render json: { error_message: 'Ya cuenta con esta dirección' }, status: :unprocessable_entity return end @address = @service.address render json: serialized_object.serializable_hash, status: :ok end def update @service = Services::UpdateAddressService.new(current_user_account, params[:id], service_params) begin case @service.call when :not_found render json: { error_message: 'Not found' }, status: :not_found when :unprocessable_entity render json: { error_messages: @service.address.errors.full_messages }, status: :unprocessable_entity else @address = @service.address render json: serialized_object.serializable_hash, status: :ok end rescue ActiveRecord::RecordNotUnique render json: { error_message: 'Ya cuenta con esta dirección' }, status: :unprocessable_entity return end end def destroy @address = Address.find_by(id: params[:id]) render json: { error_message: 'Not found' }, status: :not_found and return if @address.nil? @address.destroy render status: :see_other end private def serialized_object Serializers::AddressSerializer.new(@address) end def serialized_collection Serializers::AddressSerializer.new(@addresses.page(params[:page])) end def service_params params.permit(:number, :street, :zip_code, :country, :city) end end end