class Admission::Status < ApplicationRecord
  audited

  enum state: Admission::Applicant.states

  belongs_to :school

  has_many :applicants, dependent: :restrict_with_error

  validates :state, presence: true
  validates :name, presence: true

  validate :associated_to_applicant, if: :state_changed?

  scope :ordered, -> { order(:state) }
  scope :ordered_by_name, -> { order(:name) }
  scope :by_state, ->(state) { where(state: state) if state }
  scope :by_archived, ->(flag) { where(archived: !!flag) }

  def self.active
    where(archived: false)
  end

  def self.positioned
    order(:position)
  end

  private
    def associated_to_applicant
      return if applicants.empty?

      errors.add(:state, 'Existing Applicants are associated to this status')
    end
end
