class Admission::Agreement < ApplicationRecord
  include Castable

  audited

  cast_as_editor_content :body

  belongs_to :school

  has_many :agreement_versions, dependent: :destroy
  has_many :application_agreements, dependent: :destroy
  has_many :applicant_agreements, dependent: :restrict_with_error

  has_many :applications, through: :application_agreements
  has_many :applicants, through: :applicant_agreements
  has_many :students, through: :applicants,
    class_name: 'Student', primary_key: 'StudentID'

  validates :name, :body, presence: true

  validate :validate_html_content

  after_create :create_version
  before_update :create_version, if: :body_changed?

  scope :by_archived, ->(flag) { where(archived: flag) unless flag.nil? }

  def at_version!(datetime)
    self.body = agreement_versions.find_by(datetime: datetime).body
  end

  def self.sorted
    order(:name)
  end

  def self.positioned
    order('admission_application_agreements.position')
  end

  private
    def create_version
      agreement_versions.create(body: body)
    end

    def validate_html_content
      errors.add(:body, "can't be blank") if ActionView::Base.full_sanitizer.sanitize(body).blank?
    end
end
