defmodule Mv.Repo.Migrations.RenamePropertiesToCustomFields 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
    # Rename tables
    rename table("property_types"), to: table("custom_fields")
    rename table("properties"), to: table("custom_field_values")

    # Rename the foreign key column
    rename table("custom_field_values"), :property_type_id, to: :custom_field_id

    # Drop old foreign key constraints
    drop constraint(:custom_field_values, "properties_member_id_fkey")
    drop constraint(:custom_field_values, "properties_property_type_id_fkey")

    # Add new foreign key constraints with correct names and on_delete behavior
    alter table(:custom_field_values) do
      modify :member_id,
             references(:members,
               column: :id,
               name: "custom_field_values_member_id_fkey",
               type: :uuid,
               prefix: "public",
               on_delete: :delete_all
             )

      modify :custom_field_id,
             references(:custom_fields,
               column: :id,
               name: "custom_field_values_custom_field_id_fkey",
               type: :uuid,
               prefix: "public"
             )
    end

    # Rename indexes
    execute "ALTER INDEX IF EXISTS property_types_unique_name_index RENAME TO custom_fields_unique_name_index"

    execute "ALTER INDEX IF EXISTS properties_unique_property_per_member_index RENAME TO custom_field_values_unique_custom_field_per_member_index"
  end

  def down do
    # Rename indexes back
    execute "ALTER INDEX IF EXISTS custom_fields_unique_name_index RENAME TO property_types_unique_name_index"

    execute "ALTER INDEX IF EXISTS custom_field_values_unique_custom_field_per_member_index RENAME TO properties_unique_property_per_member_index"

    # Drop new foreign key constraints
    drop constraint(:custom_field_values, "custom_field_values_member_id_fkey")
    drop constraint(:custom_field_values, "custom_field_values_custom_field_id_fkey")

    # Add back old foreign key constraints
    alter table(:custom_field_values) do
      modify :member_id,
             references(:members,
               column: :id,
               name: "properties_member_id_fkey",
               type: :uuid,
               prefix: "public"
             )

      modify :custom_field_id,
             references(:custom_fields,
               column: :id,
               name: "properties_property_type_id_fkey",
               type: :uuid,
               prefix: "public"
             )
    end

    # Rename the foreign key column back
    rename table("custom_field_values"), :custom_field_id, to: :property_type_id

    # Rename tables back
    rename table("custom_fields"), to: table("property_types")
    rename table("custom_field_values"), to: table("properties")
  end
end
