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

  def up do
    alter table(:devices) do
      modify :site_id, :binary_id, null: true, from: {:binary_id, null: false}
    end
  end

  def down do
    # Cannot rollback if NULL site_id values exist
    execute """
    DO $$
    BEGIN
      IF EXISTS (SELECT 1 FROM devices WHERE site_id IS NULL) THEN
        RAISE EXCEPTION 'Cannot revert: devices with NULL site_id exist';
      END IF;
    END $$;
    """

    alter table(:devices) do
      modify :site_id, :binary_id, null: false
    end
  end
end
