require 'sidekiq-scheduler'

class Tep::Sync::StudentJob
  include Sidekiq::Worker

  def perform
    schools.each do |school|
      school.students.each do |student|
        next unless current_or_future_students.include?(student.id)

        batch = Sidekiq::Batch.new
        batch.jobs do
          Tep::StudentService.call(school, student.id)
        end
      end
    end
  end

  private
    def schools
      @schools ||= School
        .includes(:students)
        .joins(:school_config)
        .where(SchoolConfig: { tep_integration: true })
    end

    def school_ids
      @school_ids ||= schools.map(&:id)
    end

    def school_year_ids
      SchoolYear.where(current: true, school_id: school_ids).pluck(:id)
    end

    def current_or_future_students
      @current_or_future_students ||= SchoolYearStudent
        .where(school_id: school_ids)
        .where('EntryDate >= ?', Time.zone.now.to_date)
        .or(SchoolYearStudent.where(school_year_id: school_year_ids))
        .pluck(:student_id)
    end
end
