# typed: strict
# frozen_string_literal: true

class AddAuxTablesForDomainUsersIbUsers < ActiveRecord::Migration[7.2]
  extend T::Sig

  sig { void }
  def change
    mirai_tablespace!

    create_aux_table :domain_users, :inkbunny do |t|
      t.integer :ib_id, null: false, index: true
      t.string :name, null: false, index: true
      t.string :state, null: false
      t.timestamp :scanned_gallery_at
      t.references :deep_update_log_entry,
                   foreign_key: {
                     to_table: :http_log_entries,
                   }
      t.references :shallow_update_log_entry,
                   foreign_key: {
                     to_table: :http_log_entries,
                   }
      t.column :ib_detail_raw, :jsonb, default: {}
    end

    up_only { execute <<-SQL }
        INSERT INTO domain_users_inkbunny_aux (
          base_table_id,
          ib_id,
          name,
          state,
          scanned_gallery_at,
          deep_update_log_entry_id,
          shallow_update_log_entry_id,
          ib_detail_raw
        )
        SELECT
          id as base_table_id,
          (json_attributes->>'ib_id')::integer as ib_id,
          (json_attributes->>'name')::text as name,
          (json_attributes->>'state')::text as state,
          (json_attributes->>'scanned_gallery_at')::timestamp as scanned_gallery_at,
          (json_attributes->>'deep_update_log_entry_id')::integer as deep_update_log_entry_id,
          (json_attributes->>'shallow_update_log_entry_id')::integer as shallow_update_log_entry_id,
          (json_attributes->>'ib_detail_raw')::jsonb as ib_detail_raw
        FROM domain_users
        WHERE type = 'Domain::User::InkbunnyUser'
      SQL
  end
end
