defmodule Mv.Repo.Migrations.AddAuthorizationDomain 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
    alter table(:users) do
      add :role_id, :uuid
    end

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

    alter table(:users) do
      modify :role_id,
             references(:roles,
               column: :id,
               name: "users_role_id_fkey",
               type: :uuid,
               on_delete: :restrict,
               prefix: "public"
             )
    end

    alter table(:roles) do
      add :name, :text, null: false
      add :description, :text
      add :permission_set_name, :text, null: false
      add :is_system_role, :boolean, null: false, default: false

      add :inserted_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')")
    end

    create unique_index(:roles, [:name], name: "roles_unique_name_index")

    create index(:roles, [:permission_set_name], name: "roles_permission_set_name_index")

    create index(:users, [:role_id], name: "users_role_id_index")
  end

  def down do
    drop_if_exists index(:users, [:role_id], name: "users_role_id_index")

    drop_if_exists index(:roles, [:permission_set_name], name: "roles_permission_set_name_index")

    drop_if_exists unique_index(:roles, [:name], name: "roles_unique_name_index")

    alter table(:roles) do
      remove :updated_at
      remove :inserted_at
      remove :is_system_role
      remove :permission_set_name
      remove :description
      remove :name
    end

    drop constraint(:users, "users_role_id_fkey")

    alter table(:users) do
      modify :role_id, :uuid
    end

    drop table(:roles)

    alter table(:users) do
      remove :role_id
    end
  end
end
