defmodule Realworld.Repo.Migrations.AddTokens 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
    rename table(:users), :password, to: :hashed_password

    alter table(:users) do
      modify :username, :text, null: false
      modify :email, :text, null: false
    end

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

    create unique_index(:users, [:username], name: "users_unique_username_index")

    create table(:tokens, primary_key: false) do
      add :updated_at, :utc_datetime_usec, null: false, default: fragment("now()")
      add :created_at, :utc_datetime_usec, null: false, default: fragment("now()")
      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, [:username], name: "users_unique_username_index")

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

    alter table(:users) do
      modify :email, :text, null: true
      modify :username, :text, null: true
    end

    rename table(:users), :hashed_password, to: :password
  end
end