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

  def up do
    # Set sensor_unit for all sensors that are missing it
    # This fixes sensors created before sensor_unit was properly set in discovery code

    # Temperature sensors
    execute """
    UPDATE snmp_sensors
    SET sensor_unit = '°C'
    WHERE sensor_type = 'temperature'
      AND (sensor_unit IS NULL OR sensor_unit = '')
    """

    # Voltage sensors (only those without unit set)
    execute """
    UPDATE snmp_sensors
    SET sensor_unit = 'V'
    WHERE sensor_type = 'voltage'
      AND (sensor_unit IS NULL OR sensor_unit = '')
    """

    # Current sensors
    execute """
    UPDATE snmp_sensors
    SET sensor_unit = 'mA'
    WHERE sensor_type = 'current'
      AND (sensor_unit IS NULL OR sensor_unit = '')
    """

    # Power sensors
    execute """
    UPDATE snmp_sensors
    SET sensor_unit = 'W'
    WHERE sensor_type = 'power'
      AND (sensor_unit IS NULL OR sensor_unit = '')
    """

    # dBm sensors (optical power)
    execute """
    UPDATE snmp_sensors
    SET sensor_unit = 'dBm'
    WHERE sensor_type = 'dbm'
      AND (sensor_unit IS NULL OR sensor_unit = '')
    """

    # State sensors (leave empty, they don't have units)
    # Fan speed sensors should already have RPM
    # Frequency, rate, etc. should already have their units
  end

  def down do
    # Revert by setting units back to empty string
    execute """
    UPDATE snmp_sensors
    SET sensor_unit = ''
    WHERE sensor_type IN ('temperature', 'voltage', 'current', 'power', 'dbm')
      AND sensor_unit IN ('°C', 'V', 'mA', 'W', 'dBm')
    """
  end
end
