class ContactFamily < ApplicationRecord
  include Base::ContactFamily
  include Validatable
  include Formattable

  attr_accessor :admission

  associations_for legacy: true do |a|
    a.belongs_to :contact, autosave: true
    a.belongs_to :family
    a.belongs_to :relationship, optional: true
  end

  associations_for namespace: 'Admission' do |a|
    a.has_many :contact_revisions, dependent: :nullify
  end

  associations_for namespace: 'EdFi' do |a|
    a.has_many :logs, as: :associated, inverse_of: :associated
  end

  has_many :primary_students, through: :family

  validates :relationship_id, exclusion: { in: [0], message: 'cannot be blank' }, if: :admission

  scope :primary, -> { where(primary: true) }
  scope :emergency, -> { where(emergency: true) }
  scope :pickup, -> { where(pickup: true) }

  scope :not_in_contact_revisions, -> do
    left_joins(:admission_contact_revisions).where(admission_contact_revisions: { id: nil })
  end

  scope :by_family_1_or_2, ->(student) do
    return where(family: student.family_id) unless student.family_id_2?

    where('FamilyID = :id OR FamilyID = :id_2', id: student.family_id, id_2: student.family_id_2)
  end
end
