class MigrateExerciseUserReviewed < ActiveRecord::Migration[5.2]

  def has_comment? exercise_user, question_ids
    exercise_answer_ids = exercise_user.user&.exercise_answers.where(exercise_question_id: question_ids).pluck(:id)
    exercise_shixun_answer_ids = exercise_user.user&.exercise_shixun_answers.where(exercise_question_id: question_ids).pluck(:id)
    exercise_user.commit_status == 1 && (exercise_user.exercise_user_scores.size > 0 ||
      ExerciseAnswerComment.where(exercise_answer_id: exercise_answer_ids).or(ExerciseAnswerComment.where(exercise_shixun_answer_id: exercise_shixun_answer_ids)).exists?)
  end

  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|
        question_ids = exercise.exercise_questions.pluck(:id)
        subject_question_ids = exercise.subject_question_ids

        exercise.score_exercise_users.each do |ex_user|
          if ex_user.user.present?
            if has_comment?(ex_user, question_ids)
              ex_user.update_column("reviewed", 1)
            end

            if ex_user.subjective_score > 0.0 || ex_user.exercise_user_scores.size > 0 ||
              if ExerciseAnswerComment.where(exercise_answer_id: ex_user.user.exercise_answers.where(exercise_question_id: subject_question_ids)).exists?
                ex_user.update_column("subjective_reviewed", 1)
              end
            end
          end
        end
        puts "exercise_id: #{exercise.id}"
      end
    end
  end
end
