class CreateStudentAttendanceRecordJob < ApplicationJob
  queue_as :default

  def perform(attendance_id, group_ids)
    attendance = CourseAttendance.find_by(id: attendance_id)
    course = attendance.course
    return if attendance.blank? || course.blank?

    if group_ids.include?(0)
      students = course.students
    else
      students = course.students.where(course_group_id: group_ids)
    end

    attrs = %i[course_attendance_id user_id course_member_id course_id course_group_id created_at updated_at]

    same_attrs = {course_attendance_id: attendance.id, course_id: course.id}

    CourseMemberAttendance.bulk_insert(*attrs) do |worker|

      students.each do |student|
        worker.add same_attrs.merge(user_id: student.user_id, course_member_id: student.id, course_group_id: student.course_group_id)
      end
    end
  end
end
