defmodule Towerops.Snmp.Profiles.Vendors.CmmTest do
  use Towerops.DataCase, async: true

  import Mox

  alias Towerops.Snmp.Profiles.Vendors.Cmm
  alias Towerops.Snmp.SnmpMock

  setup :verify_on_exit!

  @client_opts [
    ip: "192.168.1.1",
    community: "public",
    version: "2c",
    port: 161,
    timeout: 5000
  ]

  describe "profile_names/0" do
    test "returns cmm and cmm4 profile names" do
      assert Cmm.profile_names() == ["cmm", "cmm4"]
    end
  end

  describe "detect_hardware/1" do
    test "detects hardware from model OID" do
      expect(SnmpMock, :get, fn _, "1.3.6.1.4.1.161.19.3.4.4.2.0", _ ->
        {:ok, "CMM4"}
      end)

      assert Cmm.detect_hardware(@client_opts) == "CMM4"
    end

    test "returns nil when OID unavailable" do
      expect(SnmpMock, :get, fn _, _, _ ->
        {:error, :no_such_object}
      end)

      assert Cmm.detect_hardware(@client_opts) == nil
    end
  end

  describe "wireless_oid_defs/0" do
    test "returns list of sensor definitions" do
      defs = Cmm.wireless_oid_defs()

      assert is_list(defs)
      assert [_ | _] = defs
    end

    test "includes power and GPS status sensors" do
      defs = Cmm.wireless_oid_defs()
      power = Enum.find(defs, &(&1.sensor_descr == "Power Status"))
      gps = Enum.find(defs, &(&1.sensor_descr == "GPS Sync Status"))

      assert power
      assert power.sensor_type == "state"
      assert gps
      assert gps.sensor_type == "state"
    end

    test "includes connected APs sensor" do
      defs = Cmm.wireless_oid_defs()
      aps = Enum.find(defs, &(&1.sensor_descr == "Connected APs"))

      assert aps
      assert aps.sensor_type == "ap-count"
    end
  end

  describe "discover_wireless_sensors/1" do
    test "discovers sensors when SNMP responds" do
      expect(SnmpMock, :get, 4, fn _, oid, _ ->
        cond do
          String.contains?(oid, "161.19.3.4.4.1.0") -> {:ok, 1}
          String.contains?(oid, "161.19.3.4.4.3.0") -> {:ok, 1}
          String.contains?(oid, "161.19.3.4.4.4.0") -> {:ok, 86_400}
          String.contains?(oid, "161.19.3.4.4.5.0") -> {:ok, 8}
          true -> {:error, :no_such_object}
        end
      end)

      sensors = Cmm.discover_wireless_sensors(@client_opts)

      assert is_list(sensors)
      assert length(sensors) == 4
    end

    test "returns empty list when no sensors respond" do
      expect(SnmpMock, :get, 4, fn _, _, _ ->
        {:error, :no_such_object}
      end)

      sensors = Cmm.discover_wireless_sensors(@client_opts)

      assert sensors == []
    end
  end
end
