defmodule Orcasite.Repo.Migrations.CreateTagsAndItemTags 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(:tags, primary_key: false) do
      add :id, :uuid, null: false, default: fragment("gen_random_uuid()"), primary_key: true
      add :name, :text, null: false
      add :description, :text
      add :slug, :text, null: 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(:tags, [:slug], name: "tags_unique_slug_index")

    create table(:item_tags, primary_key: false) do
      add :id, :uuid, null: false, default: fragment("gen_random_uuid()"), 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: "item_tags_user_id_fkey", type: :uuid)
      add :tag_id, references(:tags, column: :id, name: "item_tags_tag_id_fkey", type: :uuid)
      add :bout_id, references(:bouts, column: :id, name: "item_tags_bout_id_fkey", type: :uuid)
    end

    create index(:item_tags, [:bout_id])

    create index(:item_tags, [:user_id])

    create index(:item_tags, [:tag_id])
  end

  def down do
    drop constraint(:item_tags, "item_tags_user_id_fkey")

    drop constraint(:item_tags, "item_tags_tag_id_fkey")

    drop constraint(:item_tags, "item_tags_bout_id_fkey")

    drop_if_exists index(:item_tags, [:tag_id])

    drop_if_exists index(:item_tags, [:user_id])

    drop_if_exists index(:item_tags, [:bout_id])

    drop table(:item_tags)

    drop_if_exists unique_index(:tags, [:slug], name: "tags_unique_slug_index")

    drop table(:tags)
  end
end
