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

defmodule :"Elixir.Example.Repo.Migrations.Multi-tenancyApiKey" 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(:mt_api_keys, primary_key: false) do
      add(:id, :uuid, null: false, default: fragment("gen_random_uuid()"), primary_key: true)
      add(:api_key_hash, :binary, null: false)
      add(:expires_at, :utc_datetime_usec, 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(:mt_user,
          column: :id,
          name: "mt_api_keys_user_id_fkey",
          type: :uuid,
          prefix: "public"
        ),
        primary_key: true,
        null: false
      )

      add(:global_user_id, :uuid)
      add(:organisation_id, :uuid, null: false)
    end

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

    alter table(:mt_api_keys) do
      modify(
        :global_user_id,
        references(:global_user,
          column: :id,
          name: "mt_api_keys_global_user_id_fkey",
          type: :uuid,
          prefix: "public"
        )
      )

      modify(
        :organisation_id,
        references(:mt_organisations,
          column: :id,
          name: "mt_api_keys_organisation_id_fkey",
          type: :uuid,
          prefix: "public"
        )
      )
    end

    alter table(:global_user) do
      add(:username, :citext, null: false)
      add(:hashed_password, :text)

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

    create unique_index(:global_user, [:username], name: "global_user_username_index")
  end

  def down do
    drop_if_exists(unique_index(:global_user, [:username], name: "global_user_username_index"))

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

    drop(constraint(:mt_api_keys, "mt_api_keys_global_user_id_fkey"))

    drop(constraint(:mt_api_keys, "mt_api_keys_organisation_id_fkey"))

    alter table(:mt_api_keys) do
      modify(:organisation_id, :uuid)
      modify(:global_user_id, :uuid)
    end

    drop(table(:global_user))

    drop(constraint(:mt_api_keys, "mt_api_keys_user_id_fkey"))

    drop(table(:mt_api_keys))
  end
end
