# SPDX-FileCopyrightText: 2022 Alembic Pty Ltd
#
# SPDX-License-Identifier: MIT

defmodule Example.Repo.Migrations.MigrateResources1 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(:user_identities, primary_key: false) do
      add :refresh_token, :text
      add :access_token_expires_at, :utc_datetime_usec
      add :access_token, :text
      add :uid, :text, null: false
      add :strategy, :text, null: false
      add :id, :uuid, null: false, default: fragment("uuid_generate_v4()"), primary_key: true
      add :user_id, :uuid
    end

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

    alter table(:user_identities) do
      modify :user_id,
             references(:user,
               column: :id,
               prefix: "public",
               name: "user_identities_user_id_fkey",
               type: :uuid
             )
    end

    create unique_index(:user_identities, [:strategy, :uid, :user_id],
             name: "user_identities_unique_on_strategy_and_uid_and_user_id_index"
           )

    alter table(:user) do
      add :username, :citext, null: false
      add :hashed_password, :text
      add :created_at, :utc_datetime_usec, null: false, default: fragment("now()")
      add :updated_at, :utc_datetime_usec, null: false, default: fragment("now()")
    end

    create unique_index(:user, [:username], name: "user_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 :jti, :text, null: false, primary_key: true
    end
  end

  def down do
    drop table(:tokens)

    drop_if_exists unique_index(:user, [:username], name: "user_username_index")

    alter table(:user) do
      remove :updated_at
      remove :created_at
      remove :hashed_password
      remove :username
    end

    drop_if_exists unique_index(:user_identities, [:strategy, :uid, :user_id],
                     name: "user_identities_unique_on_strategy_and_uid_and_user_id_index"
                   )

    drop constraint(:user_identities, "user_identities_user_id_fkey")

    alter table(:user_identities) do
      modify :user_id, :uuid
    end

    drop table(:user)

    drop table(:user_identities)
  end
end