defmodule Mv.Repo.Migrations.AddAccountsDomain 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(:users, primary_key: false) do
      add :id, :uuid, null: false, default: fragment("gen_random_uuid()"), primary_key: true
      add :email, :citext, null: false
      add :hashed_password, :text
      add :oidc_id, :text

      add :member_id,
          references(:members,
            column: :id,
            name: "users_member_id_fkey",
            type: :uuid,
            prefix: "public"
          )
    end

    create unique_index(:users, [:email], name: "users_unique_email_index")

    create unique_index(:users, [:oidc_id], name: "users_unique_oidc_id_index")

    create table(:tokens, primary_key: false) do
      add :updated_at, :utc_datetime_usec,
        null: false,
        default: fragment("(now() AT TIME ZONE 'utc')")

      add :created_at, :utc_datetime_usec,
        null: false,
        default: fragment("(now() AT TIME ZONE 'utc')")

      add :extra_data, :map
      add :purpose, :text, null: false
      add :expires_at, :utc_datetime, null: false
      add :subject, :text, null: false
      add :jti, :text, null: false, primary_key: true
    end
  end

  def down do
    drop table(:tokens)

    drop_if_exists unique_index(:users, [:oidc_id], name: "users_unique_oidc_id_index")

    drop_if_exists unique_index(:users, [:email], name: "users_unique_email_index")

    drop constraint(:users, "users_member_id_fkey")

    drop table(:users)
  end
end
