defmodule Helpcenter.Repo.Migrations.AddMultitenancyTables 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_teams, primary_key: false) do
      add :id, :uuid, null: false, default: fragment("uuid_generate_v7()"), primary_key: true

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

      add :user_id,
          references(:users,
            column: :id,
            name: "user_teams_user_id_fkey",
            type: :uuid,
            prefix: "public"
          )

      add :team_id, :uuid
    end

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

    alter table(:user_teams) do
      modify :team_id,
             references(:teams,
               column: :id,
               name: "user_teams_team_id_fkey",
               type: :uuid,
               prefix: "public"
             )
    end

    create unique_index(:user_teams, [:user_id, :team_id],
             name: "user_teams_unique_article_tag_index"
           )

    alter table(:teams) do
      add :name, :text, null: false
      add :domain, :text, null: false
      add :description, :text

      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
  end

  def down do
    alter table(:teams) do
      remove :updated_at
      remove :inserted_at
      remove :description
      remove :domain
      remove :name
    end

    drop_if_exists unique_index(:user_teams, [:user_id, :team_id],
                     name: "user_teams_unique_article_tag_index"
                   )

    drop constraint(:user_teams, "user_teams_team_id_fkey")

    alter table(:user_teams) do
      modify :team_id, :uuid
    end

    drop table(:teams)

    drop constraint(:user_teams, "user_teams_user_id_fkey")

    drop table(:user_teams)
  end
end
