defmodule Towerops.Repo.Migrations.ChangeEntPhysicalIndexToJsonb do
  use Ecto.Migration

  def up do
    execute """
    ALTER TABLE profile_sensor_definitions
    ALTER COLUMN "entPhysicalIndex" TYPE jsonb
    USING CASE
      WHEN "entPhysicalIndex" IS NULL THEN NULL
      ELSE to_jsonb("entPhysicalIndex")
    END
    """
  end

  def down do
    execute """
    ALTER TABLE profile_sensor_definitions
    ALTER COLUMN "entPhysicalIndex" TYPE varchar(255)
    USING CASE
      WHEN "entPhysicalIndex" IS NULL THEN NULL
      WHEN jsonb_typeof("entPhysicalIndex") = 'string' THEN "entPhysicalIndex" #>> '{}'
      ELSE "entPhysicalIndex"::text
    END
    """
  end
end
