# SPDX-FileCopyrightText: 2020 Zach Daniel
#
# SPDX-License-Identifier: MIT

defmodule AshPostgres.TestRepo.Migrations.AddPunchlinesAndStandupClubs 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
    alter table(:jokes) do
      add(:standup_club_id, :uuid)
    end

    alter table(:comedians) do
      add(:standup_club_id, :uuid)
    end

    create table(:standup_clubs, primary_key: false) do
      add(:id, :uuid, null: false, default: fragment("gen_random_uuid()"), primary_key: true)
    end

    alter table(:jokes) do
      modify(
        :standup_club_id,
        references(:standup_clubs,
          column: :id,
          name: "jokes_standup_club_id_fkey",
          type: :uuid,
          prefix: "public"
        )
      )
    end

    alter table(:comedians) do
      modify(
        :standup_club_id,
        references(:standup_clubs,
          column: :id,
          name: "comedians_standup_club_id_fkey",
          type: :uuid,
          prefix: "public"
        )
      )
    end

    alter table(:standup_clubs) do
      add(:name, :text)

      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')")
      )
    end

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

      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(
        :joke_id,
        references(:jokes,
          column: :id,
          name: "punchlines_joke_id_fkey",
          type: :uuid,
          prefix: "public"
        )
      )
    end
  end

  def down do
    drop(constraint(:punchlines, "punchlines_joke_id_fkey"))

    drop(table(:punchlines))

    alter table(:standup_clubs) do
      remove(:updated_at)
      remove(:inserted_at)
      remove(:name)
    end

    drop(constraint(:comedians, "comedians_standup_club_id_fkey"))

    alter table(:comedians) do
      modify(:standup_club_id, :uuid)
    end

    drop(constraint(:jokes, "jokes_standup_club_id_fkey"))

    alter table(:jokes) do
      modify(:standup_club_id, :uuid)
    end

    drop(table(:standup_clubs))

    alter table(:comedians) do
      remove(:standup_club_id)
    end

    alter table(:jokes) do
      remove(:standup_club_id)
    end
  end
end
