class CreateSubjectCourseStudentJob < ApplicationJob
  queue_as :notify

  def perform(course_id)
    course = Course.find_by(id: course_id)
    return if course.blank? || course.subject.blank?

    attrs = %i[course_id user_id role created_at updated_at]
    same_attrs = {course_id: course.id, role: 4}

    Rails.logger.info("1:course.students.count:##{course.students.count}")
    CourseMember.bulk_insert(*attrs) do |worker|
      course.subject.subject_appointments.each do |app|
        Rails.logger.info("##{course.students.where(user_id: app.user_id)}")
        next if course.students.where(user_id: app.user_id).any?
        worker.add same_attrs.merge(user_id: app.user_id)
      end
    end
    Rails.logger.info("2:course.students.count:##{course.students.count}")
    course.subject.subject_appointments.destroy_all
  end
end
