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

  def up do
    # Fix devices that have snmp_community_source = "device" but no actual community string.
    # These should inherit from organization/site instead.
    #
    # Root cause: The changeset logic in update_community_source/1 was setting source = "device"
    # as the default, even when the device had no community string.
    #
    # This migration changes devices with:
    # - snmp_community_source = "device"
    # - snmp_community IS NULL or empty string
    #
    # To:
    # - snmp_community_source = "organization" (will cascade through site → org inheritance)

    execute """
    UPDATE devices
    SET snmp_community_source = 'organization'
    WHERE snmp_community_source = 'device'
      AND (snmp_community IS NULL OR snmp_community = '')
    """
  end

  def down do
    # Revert to "device" source (not ideal, but reversible)
    execute """
    UPDATE devices
    SET snmp_community_source = 'device'
    WHERE snmp_community_source = 'organization'
      AND (snmp_community IS NULL OR snmp_community = '')
    """
  end
end
