# typed: strict
class CreateDomainPostFactors < ActiveRecord::Migration[7.2]
  extend T::Sig

  sig { void }
  def change
    up_only { execute "SET DEFAULT_TABLESPACE = mirai" }

    create_factor_table(
      :domain_user_post_fav_post_factors,
      :post,
      :domain_posts,
    )

    create_factor_table(
      :domain_user_post_fav_user_factors,
      :user,
      :domain_users,
    )

    create_factor_table(
      :domain_user_user_follow_from_factors,
      :user,
      :domain_users,
    )

    create_factor_table(
      :domain_user_user_follow_to_factors,
      :user,
      :domain_users,
    )
  end

  sig do
    params(
      table_name: Symbol,
      referenced_name: Symbol,
      referenced_table_name: Symbol,
    ).void
  end
  def create_factor_table(table_name, referenced_name, referenced_table_name)
    create_table table_name, id: false do |t|
      t.references referenced_name,
                   null: false,
                   index: {
                     unique: true,
                   },
                   foreign_key: {
                     to_table: referenced_table_name,
                     validate: true,
                   }
      t.vector :embedding, limit: 32
      t.timestamps
    end

    add_index table_name,
              :embedding,
              using: :ivfflat,
              opclass: :vector_cosine_ops
  end
end
