class Discipline::StudentLog < Base::Discipline::StudentLog
  enum manager_notified: { none: 0, pan: 1, blip: 2, both: 3 }, _prefix: true

  associations_for legacy: true do |a|
    a.belongs_to :school
    a.belongs_to :student, inverse_of: :discipline_logs
    a.belongs_to :victim, class_name: 'Student', primary_key: :StudentID,
      inverse_of: :discipline_victim_logs, optional: true
    a.belongs_to :violation, keys: :DVID, inverse_of: :student_logs
    a.belongs_to :author, class_name: 'User', primary_key: :UserID,
      inverse_of: :discipline_logs
  end

  validates :datetime, presence: true

  before_create :set_quarter

  scope :by_student_ids, ->(ids) { where(student_id: ids) if ids.present? }
  scope :by_victim_ids, ->(ids) { where(victim_id: ids) if ids.present? }

  scope :by_classroom, ->(classroom) do
    joins(:student).merge(Student.by_classroom(classroom))
  end

  scope :sums_by_student_with_pending_detentions, ->(discipline_config) do
    # filter out logs by date and the SUM of points needed for a least one detention
    where(datetime: discipline_config.reset_points_start_date.to_date..Float::INFINITY)
      .having('(SUM(StudentDisciplineLogs.Points) DIV ? ) > 0', discipline_config.points_to_trigger)
      .group(:student_id)
      .sum(:points)
  end

  private
    def set_quarter
      self.quarter = school.current_year.closest_quarter(datetime)
    end
end
