defmodule Pleroma.Repo.Migrations.DropChatTables do
  use Ecto.Migration

  def up do
    # Automatically drops associated indices and constraints
    drop table(:chat_message_references)
    drop table(:chats)
  end

  def down do
    # Ecto's default primary key is bigserial, thus configure manually
    create table(:chats, primary_key: false) do
      add(:id, :uuid, primary_key: true, autogenerated: true)

      add(
        :user_id,
        references(:users, type: :uuid, on_delete: :delete_all)
        # yes, this was nullable
      )

      add(
        :recipient,
        references(:users, column: :ap_id, type: :string, on_delete: :delete_all)
        # yes, this was nullable
      )

      timestamps()
    end

    create(index(:chats, [:user_id, :recipient], unique: true))

    create table(:chat_message_references, primary_key: false) do
      add(:id, :uuid, primary_key: true, autogenerated: true)
      add(:chat_id, references(:chats, type: :uuid, on_delete: :delete_all), null: false)
      add(:object_id, references(:objects, on_delete: :delete_all), null: false)
      add(:unread, :boolean, default: true, null: false)
      timestamps()
    end

    create(index(:chat_message_references, [:chat_id, "id desc"]))
    create(unique_index(:chat_message_references, [:object_id, :chat_id]))

    create(
      index(:chat_message_references, [:chat_id],
        where: "unread = true",
        name: "unread_messages_count_index"
      )
    )
  end
end
