class Event < Base::Event
  enum exposure: { none: 0, requested: 1, approved: 2 }, _prefix: true

  belongs_to :school
  belongs_to :classroom, primary_key: 'ClassID', foreign_key: 'ClassID',
    optional: true, inverse_of: :events
  belongs_to :room, primary_key: 'FacilityID', foreign_key: 'FacilityID',
    class_name: 'Facility::Room', optional: true, inverse_of: :events

  delegate :building, to: :room, allow_nil: true

  scope :without_internal, -> { where(internal: false) }
  scope :without_classrooms, -> { where(classid: 0) }
  scope :by_rooms, ->(ids) { where(room_id: ids) }
  scope :by_date, ->(date) { where(date: date) if date }
  scope :by_date_range, ->(range) { where(date: range) if range.present? }

  scope :by_employee, ->(id) do
    query = left_joins(classroom: :class_teachers)
    query.where(ClassTeachers: { UserID: id })
      .or(query.where(class_id: 0))
      .or(query.where(exposure: :approved))
  end

  scope :by_family, ->(id) do
    query = left_joins(classroom: { class_students: :student })
    query.where(Students: { FamilyID: id }).where(Classes: { ParentViewable: true })
      .or(query.where(Students: { Family2ID: id }).where(Classes: { ParentViewable: true }))
      .or(query.where(class_id: 0))
      .or(query.where(exposure: :approved))

  end

  scope :by_student, ->(id) do
    query = left_joins(classroom: :class_students)
    query.where(ClassStudents: { StudentID: id }).where(Classes: { ParentViewable: true })
      .or(query.where(class_id: 0))
      .or(query.where(exposure: :approved))
  end
end
