class ContactAdditionalField < ApplicationRecord
  include Base::ContactAdditionalField

  acts_as_list scope: :group, column: :Sequence

  default_scope { where(model_type: 1) }

  enum type: { text: 1, multi_choice: 2, date: 3 }

  associations_for legacy: true do |a|
    a.belongs_to :school
    a.has_many :values, keys: :CSID, class_name: '::ContactAdditionalValue', inverse_of: :field
  end

  belongs_to :group, class_name: 'ContactAdditionalGroup', foreign_key: :CSGID, optional: true,
    inverse_of: :fields, counter_cache: :fields_count

  has_many :choices, -> { order(:order) }, class_name: 'ContactAdditionalChoice',
    foreign_key: :CSID, inverse_of: :field, dependent: :destroy

  accepts_nested_attributes_for :choices, update_only: true, allow_destroy: true

  before_save :remove_choices, unless: :multi_choice?

  validates :name, presence: true, length: { maximum: 32 }
  validates :description, length: { maximum: 255 }

  scope :by_ids, ->(ids) { where(id: ids) if ids }
  scope :ordered, -> { order(:position) }

  private
    def remove_choices
      choices.destroy_all
    end
end
