class AddAnswerStatisticsToGekanatorQuestionExamples < ActiveRecord::Migration[8.0]
  class MigrationGekanatorQuestionExample < ApplicationRecord
    self.table_name = 'gekanator_question_examples'
  end

  def up
    add_column :gekanator_question_examples,
               :answer_counts,
               :json,
               null: true
    add_column :gekanator_question_examples,
               :sample_count,
               :integer,
               null: false,
               default: 1

    MigrationGekanatorQuestionExample.reset_column_information
    MigrationGekanatorQuestionExample.find_each do |example|
      counts = {
        'yes' => 0,
        'no' => 0,
        'partial' => 0,
        'probably_no' => 0,
        'unknown' => 0
      }
      counts[example.answer] = 1 if counts.key?(example.answer)

      example.update_columns(
        answer_counts: counts,
        sample_count: 1)
    end

    change_column_null :gekanator_question_examples, :answer_counts, false
  end

  def down
    remove_column :gekanator_question_examples, :sample_count
    remove_column :gekanator_question_examples, :answer_counts
  end
end
