class Admission::ApplicantMedical < ApplicationRecord
  include Admissions::ApplicantApplicationBroadcastable

  audited associated_with: :applicant

  HEALTH_ISSUE_ATTRIBUTES = [
    :allergies,
    :alerts,
    :comments,
    :medication,
    :healthy,
    :asthma,
    :diabetes,
    :seizures,
    :deafness,
    :add,
    :bladder,
    :hemophiliac,
    :sicklecell,
    :sight_impairment
  ]

  belongs_to :applicant

  validates :medication, length: { maximum: 64 }
  validates :allergies, length: { maximum: 256 }

  validate :at_least_one_present_value

  after_initialize :set_defaults, if: :new_record?

  def health_issues
    HEALTH_ISSUE_ATTRIBUTES.index_with { |a| self[a] }
  end

  private
    def set_defaults
      return if (student = applicant.student).nil?
      return if (student_medical = student.student_medical).nil?

      HEALTH_ISSUE_ATTRIBUTES.each { |a| self[a] = student_medical[a] }
    end

    def at_least_one_present_value
      return if health_issues.values.any?

      errors.add(:healthy, 'Check this if you have no health issues to share with the school')
    end
end
