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

  import Mox

  alias Towerops.Snmp.Profiles.Vendors.Orolia
  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 expected profile names" do
      assert Orolia.profile_names() == ["orolia-securesync"]
    end
  end

  describe "detect_hardware/1" do
    test "returns hardware description when SNMP responds" do
      expect(SnmpMock, :get, fn _, "1.3.6.1.2.1.1.1.0", _ ->
        {:ok, "Test Device Model XYZ"}
      end)

      assert Orolia.detect_hardware(@client_opts) == "Test Device Model XYZ"
    end

    test "returns nil when SNMP fails" do
      expect(SnmpMock, :get, fn _, _, _ ->
        {:error, :timeout}
      end)

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

    test "truncates long descriptions to 64 characters" do
      long_descr = String.duplicate("A", 100)

      expect(SnmpMock, :get, fn _, "1.3.6.1.2.1.1.1.0", _ ->
        {:ok, long_descr}
      end)

      result = Orolia.detect_hardware(@client_opts)
      assert String.length(result) == 64
    end
  end

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

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

    test "each definition has required fields" do
      defs = Orolia.wireless_oid_defs()

      Enum.each(defs, fn def ->
        assert Map.has_key?(def, :oid)
        assert Map.has_key?(def, :sensor_descr)
        assert Map.has_key?(def, :sensor_type)
        assert Map.has_key?(def, :sensor_unit)
        assert Map.has_key?(def, :sensor_divisor)
      end)
    end
  end

  describe "discover_wireless_sensors/1" do
    test "discovers sensors when SNMP responds" do
      defs = Orolia.wireless_oid_defs()
      num_defs = length(defs)

      expect(SnmpMock, :get, num_defs, fn _, _oid, _ ->
        {:ok, 42}
      end)

      sensors = Orolia.discover_wireless_sensors(@client_opts)

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

    test "returns empty list when no sensors respond" do
      defs = Orolia.wireless_oid_defs()
      num_defs = length(defs)

      expect(SnmpMock, :get, num_defs, fn _, _, _ ->
        {:error, :no_such_object}
      end)

      sensors = Orolia.discover_wireless_sensors(@client_opts)

      assert sensors == []
    end
  end
end
