class MigratePostFilesToHasAuxTable < ActiveRecord::Migration[7.2]
  def up
    mirai_tablespace!

    create_aux_table :domain_post_files, :inkbunny do |t|
      t.integer :ib_id, index: true
      t.jsonb :ib_detail_raw, default: {}
      t.integer :file_order
      t.datetime :ib_created_at
      t.string :file_name
      t.string :md5_initial
      t.string :md5_full
      t.jsonb :md5s, default: []
    end

    # `ib_created_at` string is in format like `2019-10-11T16:57:19.945Z` - aka iso8601 zulu time
    # so we need to convert it to utc time
    up_only { execute <<-SQL }
        INSERT INTO domain_post_files_inkbunny_aux (
          base_table_id,
          ib_id,
          ib_detail_raw,
          file_order, ib_created_at,
          file_name,
          md5_initial,
          md5_full,
          md5s
        )
        SELECT
          id as base_table_id,
          (json_attributes->>'ib_id')::integer as ib_id,
          (json_attributes->>'ib_detail_raw')::jsonb as ib_detail_raw,
          (json_attributes->>'file_order')::integer as file_order,
          (json_attributes->>'ib_created_at')::timestamp as ib_created_at,
          (json_attributes->>'file_name')::text as file_name,
          (json_attributes->>'md5_initial')::text as md5_initial,
          (json_attributes->>'md5_full')::text as md5_full,
          (json_attributes->>'md5s')::jsonb as md5s
        FROM domain_post_files
        WHERE type = 'Domain::PostFile::InkbunnyPostFile'
      SQL

    # TODO - add foreign key constraints on base_table_id
  end
end
