class ClassGrade < Base::ClassGrade
  audited

  enum status: { dropped: -2, absent: -1, none: 0, excused: 1, missing: 3, late: 4 }, _prefix: true

  associations_for legacy: true do |a|
    a.belongs_to :school
    a.belongs_to :classroom, keys: :ClassID
    a.belongs_to :class_assignment, keys: :CAID
    a.belongs_to :student
    a.belongs_to :author, class_name: 'User', primary_key: :UserID
  end

  after_initialize :set_school, if: :new_record?

  scope :by_status, ->(status) { where(status: status) if status }
  scope :missing, -> { where(status: :missing) }
  scope :without_status, ->(status) { where.not(status: status) if status }
  scope :by_student, ->(student) { where(student_id: student) if student }
  scope :by_term, ->(term) do
    joins(:class_assignment).where(ClassAssignments: { Quarter: term }) if term
  end

  scope :by_parent_viewable, -> { joins(:classroom).merge(Classroom.by_parent_viewable(true)) }

  scope :with_classroom_students, -> do
    joins(<<~SQL)
      INNER JOIN ClassStudents
      ON ClassStudents.ClassID = ClassGrades.ClassID
      AND ClassStudents.StudentID = ClassGrades.StudentID
    SQL
  end

  private
    def set_school
      self.school = student.school if student_id?
    end
end
