# typed: true
class AddPostableTypeEnum < ActiveRecord::Migration[7.2]
  def up
    execute <<-SQL
      CREATE TYPE postable_type AS ENUM ('Domain::Fa::Post', 'Domain::E621::Post', 'Domain::Inkbunny::Post');
    SQL

    # Create a temporary column with the new type
    add_column :indexed_posts, :postable_type_enum, :postable_type

    # Copy data from the old column to the new one
    execute <<-SQL
      UPDATE indexed_posts
      SET postable_type_enum = postable_type::postable_type;
    SQL

    # Remove the old column and rename the new one
    remove_column :indexed_posts, :postable_type
    rename_column :indexed_posts, :postable_type_enum, :postable_type

    # make the new column non-nullable
    change_column_null :indexed_posts, :postable_type, false

    # index on the polymorphic association
    add_index :indexed_posts, %i[postable_id postable_type], unique: true
  end

  def down
    # Create a temporary string column
    add_column :indexed_posts, :postable_type_string, :string

    # Copy data from enum to string
    execute <<-SQL
      UPDATE indexed_posts
      SET postable_type_string = postable_type::text;
    SQL

    # Remove enum column and rename string column
    remove_column :indexed_posts, :postable_type
    rename_column :indexed_posts, :postable_type_string, :postable_type

    # Drop the enum type
    execute <<-SQL
      DROP TYPE postable_type;
    SQL

    change_column_null :indexed_posts, :postable_type, true
  end
end
