class Admission::ContactRevision < ApplicationRecord
  include Admissions::ApplicantApplicationBroadcastable
  include Personable
  include Validatable

  attr_accessor :skip_validation

  belongs_to :school_year
  belongs_to :family, class_name: '::Family'
  belongs_to :contact_family, optional: true
  belongs_to :relationship
  belongs_to :title, optional: true
  belongs_to :country, class_name: 'IsoCountry'

  delegate :school, to: :family
  delegate :contact, to: :contact_family, allow_nil: true

  alias_attribute :zip_code, :zip

  CONTACT_ATTRIBUTES = [
    :title_id,
    :first_name,
    :last_name,
    :address,
    :address_ext,
    :city,
    :state,
    :zip,
    :work_phone,
    :home_phone,
    :cell_phone,
    :email,
    :country_id
  ]

  CONTACT_FAMILY_ATTRIBUTES = [:relationship_id, :primary, :emergency, :pickup]

  ALL_ATTRIBUTES = CONTACT_ATTRIBUTES + CONTACT_FAMILY_ATTRIBUTES + [:contact_family_id]

  validate :required_fields, unless: :skip_validation

  validates :first_name, :last_name, presence: true
  validates :zip, length: { maximum: 10 }
  validates :zip, length: { minimum: 5 }, if: -> { country_id == 236 && zip? }
  validates :relationship_id, exclusion: { in: [0], message: 'cannot be blank' }

  after_initialize :set_defaults, if: :new_record?

  scope :by_school_year, ->(school_year) { where(school_year_id: school_year) if school_year }

  def self.with_non_primary_emergency_contact(school_year)
    find_by(school_year: school_year, emergency: true, primary: false)
  end

  def self.ordered
    order(:last_name, :first_name)
  end

  def apply!
    return false if applied

    if contact_family_id.nil?
      self.updated_at = Time.zone.now
      self.contact_family = family.contact_families.build
      contact_family.contact = family.school.contacts.build
    end

    contact = contact_family.contact
    CONTACT_ATTRIBUTES.each { |a| contact[a] = public_send(a) }
    CONTACT_FAMILY_ATTRIBUTES.each { |a| contact_family[a] = public_send(a) }

    contact_family.save!
    contact.save!
  end

  private
    def set_defaults
      self.country_id = contact&.country_id || school.country_id
      return if contact_family.nil?

      self.family = contact_family.family
      contact = contact_family.contact

      CONTACT_ATTRIBUTES.each { |a| self[a] = contact[a] if self[a].to_s.blank? }

      (CONTACT_FAMILY_ATTRIBUTES - [:country_id]).each do |attribute|
        self[attribute] = contact_family[attribute] if self[attribute].blank?
      end

      self.title = nil if title_id.zero?
    end

    def required_fields
      fields = school.admission_contact_revision_fields.with_required.pluck(:field)
      fields.each do |field|
        field = :zip if field.to_sym == :zip_code
        field = :relationship_id if field.to_sym == :relationship
        next if field.to_sym == :emergency_contact
        next if send(field).present?

        errors.add(field, 'cannot be blank')
      end
    end
end
