# typed: strict
# frozen_string_literal: true

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

  sig { void }
  def change
    mirai_tablespace!

    create_aux_table :domain_users, :e621 do |t|
      t.integer :e621_id, null: false, index: true
      t.string :name, null: false, index: true
      t.boolean :favs_are_hidden
      t.integer :num_other_favs_cached
      t.string :scanned_favs_status
      t.datetime :registered_at
    end

    up_only { execute <<-SQL }
        INSERT INTO domain_users_e621_aux (
          base_table_id,
          e621_id,
          name,
          favs_are_hidden,
          num_other_favs_cached,
          scanned_favs_status,
          registered_at
        )
        SELECT
          id as base_table_id,
          (json_attributes->>'e621_id')::integer as e621_id,
          (json_attributes->>'name')::text as name,
          (json_attributes->>'favs_are_hidden')::boolean as favs_are_hidden,
          (json_attributes->>'num_other_favs_cached')::integer as num_other_favs_cached,
          (json_attributes->>'scanned_favs_status')::text as scanned_favs_status,
          (json_attributes->>'registered_at')::timestamp as registered_at
        FROM domain_users
        WHERE type = 'Domain::User::E621User'
      SQL
  end
end
