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

defmodule AshPostgres.TestRepo.Migrations.MigrateResources59 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(:products, primary_key: false) do
      add(:id, :uuid, null: false, default: fragment("gen_random_uuid()"), primary_key: true)
      add(:name, :text)
    end

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

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

    alter table(:orders) do
      modify(
        :customer_id,
        references(:customers,
          column: :id,
          name: "orders_customer_id_fkey",
          type: :uuid,
          prefix: "public"
        )
      )

      modify(
        :product_id,
        references(:products,
          column: :id,
          name: "orders_product_id_fkey",
          type: :uuid,
          prefix: "public"
        )
      )
    end

    alter table(:customers) do
      add(:name, :text)
    end
  end

  def down do
    alter table(:customers) do
      remove(:name)
    end

    drop(constraint(:orders, "orders_customer_id_fkey"))

    drop(constraint(:orders, "orders_product_id_fkey"))

    alter table(:orders) do
      modify(:product_id, :uuid)
      modify(:customer_id, :uuid)
    end

    drop(table(:customers))

    drop(table(:orders))

    drop(table(:products))
  end
end
