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

defmodule AshPostgres.TestRepo.Migrations.AddResourcesForSubqueryTest 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(:subquery_through, primary_key: false) do
      add :parent_id, :uuid, null: false, primary_key: true
      add :child_id, :uuid, null: false, primary_key: true
    end

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

    alter table(:subquery_through) do
      modify :parent_id,
             references(:subquery_parent,
               column: :id,
               name: "subquery_through_parent_id_fkey",
               type: :uuid,
               prefix: "public"
             )
    end

    alter table(:subquery_parent) do
      add :owner_email, :text
      add :other_owner_email, :text
      add :visible, :boolean
    end

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

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

      add :parent_id,
          references(:subquery_parent,
            column: :id,
            name: "subquery_access_parent_id_fkey",
            type: :uuid,
            prefix: "public"
          )

      add :email, :text
    end
  end

  def down do
    drop constraint(:subquery_access, "subquery_access_parent_id_fkey")

    drop table(:subquery_access)

    drop table(:subquery_child)

    alter table(:subquery_parent) do
      remove :visible
      remove :other_owner_email
      remove :owner_email
    end

    drop constraint(:subquery_through, "subquery_through_parent_id_fkey")

    alter table(:subquery_through) do
      modify :parent_id, :uuid
    end

    drop table(:subquery_parent)

    drop table(:subquery_through)
  end
end
