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

defmodule AshPostgres.TestRepo.Migrations.MigrateResources8 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(:users) do
      add :organization_id, :uuid
    end

    alter table(:posts) do
      add :organization_id, :uuid
    end

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

    alter table(:users) do
      modify :organization_id,
             references(:orgs,
               column: :id,
               prefix: "public",
               name: "users_organization_id_fkey",
               type: :uuid
             )
    end

    alter table(:posts) do
      modify :organization_id,
             references(:orgs,
               column: :id,
               prefix: "public",
               name: "posts_organization_id_fkey",
               type: :uuid
             )
    end

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

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

    drop constraint(:posts, "posts_organization_id_fkey")

    alter table(:posts) do
      modify :organization_id, :uuid
    end

    drop constraint(:users, "users_organization_id_fkey")

    alter table(:users) do
      modify :organization_id, :uuid
    end

    drop table(:orgs)

    alter table(:posts) do
      remove :organization_id
    end

    alter table(:users) do
      remove :organization_id
    end
  end
end