defmodule Oban.Pro.Migrations.DynamicCron do
  @moduledoc false

  use Ecto.Migration

  def change(_opts \\ []), do: :ok

  def up(_opts \\ []), do: :ok

  def down(_opts \\ []), do: :ok
end

defmodule Oban.Pro.Migrations.DynamicQueues do
  @moduledoc false

  use Ecto.Migration

  def change(_opts \\ []), do: :ok

  def up(_opts \\ []), do: :ok

  def down(_opts \\ []), do: :ok
end

defmodule Oban.Pro.Migrations.Producers do
  @moduledoc false

  use Ecto.Migration

  def change(_opts \\ []), do: :ok

  def up(_opts \\ []), do: :ok

  def down(_opts \\ []), do: :ok
end

defmodule Oban.Pro.Migrations.V100 do
  @moduledoc false

  use Ecto.Migration

  defmacrop utc_now do
    quote do
      fragment("timezone('utc', now())")
    end
  end

  def up_ddl(opts) do
    create_if_not_exists table(:oban_producers, primary_key: false, prefix: opts.prefix) do
      add :uuid, :uuid, primary_key: true, null: false
      add :name, :text, null: false
      add :node, :text, null: false
      add :queue, :text, null: false
      add :meta, :map, null: false, default: %{}

      add :started_at, :utc_datetime_usec, null: false, default: utc_now()
      add :updated_at, :utc_datetime_usec, null: false, default: utc_now()
    end

    if opts.unlogged do
      execute "ALTER TABLE #{opts.quoted}.oban_producers SET UNLOGGED"
    end

    create_if_not_exists table(:oban_crons, primary_key: false, prefix: opts.prefix) do
      add :name, :text, primary_key: true, null: false
      add :expression, :text, null: false
      add :worker, :text, null: false
      add :opts, :map, null: false
      add :insertions, {:array, :utc_datetime_usec}, default: [], null: false
      add :paused, :boolean, null: false, default: false
      add :lock_version, :integer, default: 1

      add :inserted_at, :utc_datetime_usec, null: false, default: utc_now()
      add :updated_at, :utc_datetime_usec, null: false, default: utc_now()
    end

    create_if_not_exists table(:oban_queues, primary_key: false, prefix: opts.prefix) do
      add :name, :text, primary_key: true, null: false
      add :opts, :map, null: false, default: %{}
      add :only, :map, null: false, default: %{}
      add :lock_version, :integer, default: 1

      add :inserted_at, :utc_datetime_usec, null: false, default: utc_now()
      add :updated_at, :utc_datetime_usec, null: false, default: utc_now()
    end
  end

  def up_idx(_opts), do: :ok

  def down_ddl(opts) do
    drop_if_exists table(:oban_queues, prefix: opts.prefix)
    drop_if_exists table(:oban_crons, prefix: opts.prefix)
    drop_if_exists table(:oban_producers, prefix: opts.prefix)
  end

  def down_idx(_opts), do: :ok
end
