class EmployeePhone < Phone
  audited associated_with: :employee

  enum code: { fax: 0, home: 1, mobile: 2, other: 3, work: 4 }

  attr_accessor :skip_sync

  belongs_to :employee, foreign_key: :associated_id, inverse_of: :phones

  delegate :communication_user, to: :employee, allow_nil: true

  after_save :sync_freshdesk_contact, if: -> { mobile? || work? }
  after_save :sync_legacy_phones, unless: :skip_sync

  before_destroy :remove_legacy_phones

  validates :code, uniqueness: { scope: :associated_id }

  private
    def sync_legacy_phones
      case code.to_sym
      when :home
        employee.update(legacy_home_phone: number)
      when :work
        employee.update(legacy_work_phone: number)
      when :mobile
        employee.update(legacy_cell_phone: number)
      when :fax
        employee.update!(legacy_fax_phone: number)
      when :other
        employee.update(legacy_work_phone_2: number)
      end
    end

    def remove_legacy_phones
      case code.to_sym
      when :home
        employee.update(legacy_home_phone: '')
      when :work
        employee.update(legacy_work_phone: '')
      when :mobile
        employee.update(legacy_cell_phone: '')
      when :fax
        employee.update(legacy_fax_phone: '')
      when :other
        employee.update(legacy_work_phone_2: '')
      end
    end

    def sync_freshdesk_contact
      return unless employee.support_id?

      Freshdesk::ContactService.new(employee).update
    end
end
