defmodule Mv.Repo.Migrations.InitialMigration 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(:property_types, primary_key: false) do
      add :id, :uuid, null: false, default: fragment("gen_random_uuid()"), primary_key: true
      add :name, :text, null: false
      add :value_type, :text, null: false
      add :description, :text
      add :immutable, :boolean, null: false, default: false
      add :required, :boolean, null: false, default: false
    end

    create unique_index(:property_types, [:name], name: "property_types_unique_name_index")

    create table(:properties, primary_key: false) do
      add :id, :uuid, null: false, default: fragment("gen_random_uuid()"), primary_key: true
      add :value, :map
      add :member_id, :uuid
      add :property_type_id, :uuid
    end

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

    alter table(:properties) do
      modify :member_id,
             references(:members,
               column: :id,
               name: "properties_member_id_fkey",
               type: :uuid,
               prefix: "public"
             )

      modify :property_type_id,
             references(:property_types,
               column: :id,
               name: "properties_property_type_id_fkey",
               type: :uuid,
               prefix: "public"
             )
    end
  end

  def down do
    drop constraint(:properties, "properties_member_id_fkey")

    drop constraint(:properties, "properties_property_type_id_fkey")

    alter table(:properties) do
      modify :property_type_id, :uuid
      modify :member_id, :uuid
    end

    drop table(:members)

    drop table(:properties)

    drop_if_exists unique_index(:property_types, [:name],
                     name: "property_types_unique_name_index"
                   )

    drop table(:property_types)
  end
end
