class MigrateCouresMemberGroup < ActiveRecord::Migration[5.2]
  def change
    course_ids = [377, 657, 715, 777, 973, 1093, 1131, 1180, 1309, 1920, 2037, 2346, 2354, 2493, 2752, 2920, 3000,
                  3141, 3240, 3350, 3351, 3353, 3387, 3533, 3796]

    courses = Course.where(id: course_ids)

    courses.each do |course|
      group_ids = course.course_groups.pluck(:id) + [0]
      course.course_members.where.not(course_group_id: group_ids).each do |member|
        if CourseGroup.where(course_id: course.id, name: member.course_group_name).exists?
          new_group = CourseGroup.where(course_id: course.id, name: member.course_group_name).first
        else
          # position = CourseGroup.where(course_id: course.id).order("position desc").first&.position.to_i + 1
          new_group = course.course_groups.create!(name: member.course_group_name)
          course.exercise_group_settings.where(course_group_id: member.course_group_id).update_all(course_group_id: new_group.id)
          course.attachment_group_settings.where(course_group_id: member.course_group_id).update_all(course_group_id: new_group.id)
          HomeworkGroupReview.where(homework_common_id: course.homework_commons.pluck(:id)).where(course_group_id: member.course_group_id).update_all(course_group_id: new_group.id)
          course.homework_group_settings.where(course_group_id: member.course_group_id).update_all(course_group_id: new_group.id)
        end
        member.update!(course_group_id: new_group.id)
      end
    end
  end
end
