class StudentAdditionalId < AdditionalId
  audited associated_with: :student

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

  attr_accessor :skip_sync

  belongs_to :student, foreign_key: :associated_id, inverse_of: :additional_ids

  delegate :school, to: :student

  after_save :sync_legacy_ids, unless: :skip_sync
  after_save :delete_ed_fi_identity, if: -> { school.ed_fi_system_indiana? }

  before_destroy :remove_legacy_ids

  validates :code, uniqueness: { scope: :associated_id }
  validates :number, length: { is: 10, message: '10 digits required' }, numericality: true,
    if: :indiana_settlement?

  validate :validate_uniqueness, unless: :indiana_settlement?

  private
    def sync_legacy_ids
      case code.to_sym
      when :school
        student.update(external_id: number)
      when :state
        student.update(state_id: number)
      end
    end

    def remove_legacy_ids
      case code.to_sym
      when :school
        student.update(external_id: nil)
      when :state
        student.update(state_id: nil)
      end
    end

    def validate_uniqueness
      ids = school.student_additional_ids.public_send(code).where.not(id: id).pluck(:number)

      errors.add(:number, 'ID already exists') if ids.include?(number)
    end

    def delete_ed_fi_identity
      return unless state?

      associated&.ed_fi_identity&.destroy
    end
end
