class EmployeeAdditionalField < ApplicationRecord
  include Base::EmployeeAdditionalField

  acts_as_list scope: :group, column: :Sequence

  enum type: { text: 1, multi_choice: 2, date: 3 }
  enum validation_type: { nothing: 0, number: 1, email: 2, min_length: 3, max_length: 4, regex: 5 }

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

  belongs_to :group, class_name: 'EmployeeAdditionalGroup', foreign_key: :USGID, optional: true,
    inverse_of: :fields, touch: true

  has_many :choices, -> { order(:order) }, class_name: 'EmployeeAdditionalChoice',
    foreign_key: :USID, 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 :validation_pattern, length: { maximum: 64 }
  validates :description, length: { maximum: 255 }
  validate do |employee_additional_field|
    if employee_additional_field.validation_pattern.present? &&
        employee_additional_field.validation_type == 'regex'
      begin
        Regexp.new(employee_additional_field.validation_pattern)
      rescue RegexpError => e
        errors.add(:validation_pattern, 'Validation pattern is invalid regex')
      end
    end
  end

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

  def employees_with_values
    values.distinct.pluck(:employee_id).count
  end

  def destroy_attached_values
    values.destroy_all
  end

  private
    def remove_choices
      choices.destroy_all
    end
end
