defmodule Towerops.Workers.DiscoveryWorker do
  @moduledoc """
  Background worker for SNMP device discovery.

  Enqueued when:
  - A new device is created with SNMP enabled
  - An existing device's SNMP configuration is changed
  - User manually triggers discovery via "Rediscover Device" button

  Queue: discovery
  """

  alias Towerops.Devices
  alias Towerops.Snmp

  require Logger

  @doc """
  Performs SNMP discovery for a device.

  ## Parameters
  - device_id: The UUID of the device to discover

  ## Returns
  - :ok on success
  - {:error, reason} on failure
  """
  def perform(device_id) do
    Logger.info("Starting SNMP discovery for device #{device_id}")

    device = Devices.get_device!(device_id)

    case Snmp.discover_device(device) do
      {:ok, _snmp_device} ->
        Logger.info("SNMP discovery completed successfully for device #{device_id}")
        :ok

      {:error, reason} ->
        Logger.error("SNMP discovery failed for device #{device_id}: #{inspect(reason)}")
        {:error, reason}
    end
  rescue
    Ecto.NoResultsError ->
      Logger.error("Device #{device_id} not found")
      {:error, :device_not_found}
  end
end
