defmodule WandererApp.Repo.Migrations.AddWebhookSubscriptions do
  @moduledoc """
  Updates resources based on their most recent snapshots.

  This file was autogenerated with `mix ash_postgres.generate_migrations`
  """

  use Ecto.Migration

  def up do
    create table(:map_webhook_subscriptions_v1, primary_key: false) do
      add :id, :uuid, null: false, default: fragment("gen_random_uuid()"), primary_key: true

      add :map_id,
          references(:maps_v1,
            column: :id,
            name: "map_webhook_subscriptions_v1_map_id_fkey",
            type: :uuid,
            prefix: "public"
          ),
          null: false

      add :url, :text, null: false
      add :events, {:array, :text}, null: false, default: []
      add :active?, :boolean, null: false, default: true
      add :last_delivery_at, :utc_datetime
      add :last_error, :text
      add :last_error_at, :utc_datetime
      add :consecutive_failures, :bigint, null: false, default: 0

      add :inserted_at, :utc_datetime_usec,
        null: false,
        default: fragment("(now() AT TIME ZONE 'utc')")

      add :updated_at, :utc_datetime_usec,
        null: false,
        default: fragment("(now() AT TIME ZONE 'utc')")

      add :encrypted_secret, :binary, null: false
    end

    create unique_index(:map_webhook_subscriptions_v1, [:map_id, :url],
             name: "map_webhook_subscriptions_v1_unique_url_per_map_index"
           )
  end

  def down do
    drop_if_exists unique_index(:map_webhook_subscriptions_v1, [:map_id, :url],
                     name: "map_webhook_subscriptions_v1_unique_url_per_map_index"
                   )

    drop constraint(:map_webhook_subscriptions_v1, "map_webhook_subscriptions_v1_map_id_fkey")

    drop table(:map_webhook_subscriptions_v1)
  end
end
