class Nursing::Prescription < ApplicationRecord
  include Base::Nursing::Prescription

  audited

  belongs_to :student, foreign_key: :StudentID, inverse_of: :nursing_prescriptions

  has_many :distributions, class_name: '::Nursing::PrescriptionDistribution', foreign_key: :SMSCHID,
    dependent: :restrict_with_error, inverse_of: :prescription

  delegate :school, to: :student

  validates :medication, presence: true, length: { maximum: 64 }
  validates :route, length: { maximum: 64 }
  validates :dose, length: { maximum: 32 }
  validates :schedule, length: { maximum: 128 }

  scope :by_date, ->(date) do
    return unless date

    empty_value = [nil, '', 0000-00-00]

    where('StartDate <= ?', date).where('StopDate >= ?', date)
      .or(where(start_date: empty_value).where(stop_date: empty_value))
      .or(where('StartDate <= ?', date).where(stop_date: empty_value))
  end
end
