class EmployeeAdditionalId < AdditionalId
  audited associated_with: :employee

  enum code: { school: 0, state: 1, social_security_number: 2 }

  CODE_DISPLAY = {
    school: 'School-issued ID',
    state: 'State-issued ID'
  }

  attr_accessor :skip_sync

  belongs_to :employee, foreign_key: :associated_id, inverse_of: :additional_ids

  delegate :school, to: :employee

  after_save :sync_legacy_ids, unless: :skip_sync

  before_destroy :remove_legacy_ids

  after_commit :delete_ed_fi_identity, if: -> { school.ed_fi_system_indiana? }

  validates :code, uniqueness: { scope: :associated_id }
  validates :number, length: { is: 4 }, numericality: true, if: :social_security_number?

  private
    def sync_legacy_ids
      case code.to_sym
      when :school
        employee.update(employee_id: number)
      when :state
        employee.update(StateID: number)
      when :social_security_number
        employee.update(SSN: number)
      end
    end

    def remove_legacy_ids
      case code.to_sym
      when :school
        employee.update(employee_id: nil)
      when :state
        employee.update(StateID: nil)
      when :social_security_number
        employee.update(SSN: nil)
      end
    end

    def delete_ed_fi_identity
      return unless state?

      employee&.ed_fi_identity&.destroy
    end
end
