defmodule Mv.Repo.Migrations.AddSlugToCustomFields 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
    # Step 1: Add slug column as nullable first
    alter table(:custom_fields) do
      add :slug, :text, null: true
    end

    # Step 2: Generate slugs for existing custom fields
    execute("""
    UPDATE custom_fields
    SET slug = lower(
      regexp_replace(
        regexp_replace(
          regexp_replace(name, '[^a-zA-Z0-9\\s-]', '', 'g'),
          '\\s+', '-', 'g'
        ),
        '-+', '-', 'g'
      )
    )
    WHERE slug IS NULL
    """)

    # Step 3: Make slug NOT NULL
    alter table(:custom_fields) do
      modify :slug, :text, null: false
    end

    # Step 4: Create unique index
    create unique_index(:custom_fields, [:slug], name: "custom_fields_unique_slug_index")
  end

  def down do
    drop_if_exists unique_index(:custom_fields, [:slug], name: "custom_fields_unique_slug_index")

    alter table(:custom_fields) do
      remove :slug
    end
  end
end
