# typed: strict
class AddIbPoolIdToPools < ActiveRecord::Migration[7.0]
  extend T::Sig

  sig { void }
  def change
    add_column :domain_inkbunny_pools, :ib_pool_id, :bigint
    add_index :domain_inkbunny_pools, :ib_pool_id, unique: true
    add_column :domain_inkbunny_pools, :count, :integer

    # ib_post_id should have been unique, but it wasn't. used for foreign key
    # constraint.
    add_index :domain_inkbunny_posts,
              :ib_post_id,
              unique: true,
              if_not_exists: true

    tablespace_name =
      (
        if ActiveRecord::Base
             .connection
             .execute("SELECT 1 FROM pg_tablespace WHERE spcname = 'mirai';")
             .any?
          "mirai"
        else
          "pg_default"
        end
      )

    create_table :domain_inkbunny_pool_joins, tablespace: tablespace_name do |t|
      t.references :post,
                   to_table: :domain_inkbunny_posts,
                   validate: true,
                   index: false
      t.references :pool, to_table: :domain_inkbunny_pools, validate: true
      t.references :left_post, to_table: :domain_inkbunny_posts, validate: true
      t.references :right_post, to_table: :domain_inkbunny_posts, validate: true

      t.index %i[post_id pool_id], unique: true
    end

    up_only { ActiveRecord::Base.connection.execute(<<-SQL) }
        ALTER TABLE domain_inkbunny_pool_joins SET TABLESPACE #{tablespace_name};
        ALTER INDEX domain_inkbunny_pool_joins_pkey SET TABLESPACE #{tablespace_name};
        ALTER INDEX index_domain_inkbunny_pool_joins_on_post_id_and_pool_id SET TABLESPACE #{tablespace_name};
        ALTER INDEX index_domain_inkbunny_pool_joins_on_pool_id SET TABLESPACE #{tablespace_name};
        ALTER INDEX index_domain_inkbunny_pool_joins_on_left_post_id SET TABLESPACE #{tablespace_name};
        ALTER INDEX index_domain_inkbunny_pool_joins_on_right_post_id SET TABLESPACE #{tablespace_name};
      SQL
  end
end
