class MigrateExerciseUserStatus < ActiveRecord::Migration[5.2]

  def change
    exercises = Exercise.where("exercise_status > 1")
    exercises.includes(:exercise_questions, score_exercise_users: [:exercise_user_scores, :user]).find_in_batches(batch_size: 200) do |p|
      Parallel.each(p, in_threads: 4) do |exercise|
        subject_question_ids = exercise.exercise_questions.select{|question| question.question_type == 4}.map(&:id)
        if subject_question_ids.blank?
          exercise.score_exercise_users.update_all(reviewed: 1, subjective_reviewed: 1)
        else
          exercise.score_exercise_users.each do |ex_user|
            if ex_user.exercise_user_scores.size > 0
              ex_user.update_columns(reviewed: 1, subjective_reviewed: 1)
            else
              undo_status = true
              teacher_comment_status = false
              exercise.exercise_questions.select{|question| question.question_type == 4}.each do |q|
                answer = q.exercise_answers.find_by(user_id: ex_user.user_id)
                undo_status &= (answer.blank? || answer.answer_text.blank?)
                teacher_comment_status ||= answer&.exercise_answer_comments.present?
              end

              reviewed = undo_status || teacher_comment_status
              subjective_reviewed = reviewed
              ex_user.update_columns(reviewed: reviewed, subjective_reviewed: subjective_reviewed)
            end
          end
        end
        puts "exercise_id: #{exercise.id}"
      end
    end
  end
end
