defmodule Contactly.Repo.Migrations.CreateContactsTable 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(:contacts, primary_key: false) do
      add :id, :uuid, null: false, default: fragment("gen_random_uuid()"), primary_key: true
      add :name, :text, null: false
      add :email, :citext, null: false
      add :phone, :text, null: false

      add :created_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 :user_id,
          references(:users,
            column: :id,
            name: "contacts_user_id_fkey",
            type: :uuid,
            prefix: "public",
            on_delete: :delete_all
          ),
          null: false
    end

    create index(:contacts, [:user_id])

    create unique_index(:contacts, [:email], name: "contacts_unique_email_index")

    create unique_index(:contacts, [:phone], name: "contacts_unique_phone_index")
  end

  def down do
    drop_if_exists unique_index(:contacts, [:phone], name: "contacts_unique_phone_index")

    drop_if_exists unique_index(:contacts, [:email], name: "contacts_unique_email_index")

    drop_if_exists index(:contacts, [:user_id])

    drop constraint(:contacts, "contacts_user_id_fkey")

    drop table(:contacts)
  end
end
