class Phone < ApplicationRecord
  belongs_to :associate, polymorphic: true, optional: true

  validates :number, presence: true
  validates :country_code, presence: true, length: { maximum: 2 }

  before_update :remove_from_communication_user

  before_destroy :remove_from_communication_user

  private
    def remove_from_communication_user
      return unless communication_user

      previous_number = number_was.tr('^0-9', '')
      if previous_number == communication_user.voice_phone
        communication_user.update(voice_phone: '')
      end

      if previous_number == communication_user.message_phone
        communication_user.update(message_phone: '')
      end
    end
end
