defmodule Towerops.Snmp.NeighborCleanupWorkerTest do
  use Towerops.DataCase, async: false

  import Towerops.AccountsFixtures

  alias Towerops.Snmp
  alias Towerops.Snmp.Device
  alias Towerops.Snmp.Interface
  alias Towerops.Snmp.Neighbor
  alias Towerops.Snmp.NeighborCleanupWorker

  setup do
    user = user_fixture()
    {:ok, organization} = Towerops.Organizations.create_organization(%{name: "Test Org"}, user.id)

    {:ok, site} =
      Towerops.Sites.create_site(%{
        name: "Test Site",
        organization_id: organization.id
      })

    {:ok, device_schema1} =
      Towerops.Devices.create_device(%{
        name: "Test Switch 1",
        ip_address: "192.168.1.1",
        snmp_enabled: true,
        snmp_version: "2c",
        snmp_community: "public",
        snmp_port: 161,
        site_id: site.id
      })

    {:ok, device_schema2} =
      Towerops.Devices.create_device(%{
        name: "Test Switch 2",
        ip_address: "192.168.1.2",
        snmp_enabled: true,
        snmp_version: "2c",
        snmp_community: "public",
        snmp_port: 161,
        site_id: site.id
      })

    device1 =
      %Device{}
      |> Device.changeset(%{
        device_id: device_schema1.id,
        sys_name: "test-switch-1",
        sys_descr: "Test Switch 1"
      })
      |> Repo.insert!()

    device2 =
      %Device{}
      |> Device.changeset(%{
        device_id: device_schema2.id,
        sys_name: "test-switch-2",
        sys_descr: "Test Switch 2"
      })
      |> Repo.insert!()

    interface1 =
      %Interface{}
      |> Interface.changeset(%{
        snmp_device_id: device1.id,
        if_index: 1,
        if_descr: "GigabitEthernet0/1",
        if_name: "Gi0/1",
        if_type: 6,
        if_oper_status: "up"
      })
      |> Repo.insert!()

    interface2 =
      %Interface{}
      |> Interface.changeset(%{
        snmp_device_id: device2.id,
        if_index: 1,
        if_descr: "GigabitEthernet0/1",
        if_name: "Gi0/1",
        if_type: 6,
        if_oper_status: "up"
      })
      |> Repo.insert!()

    %{
      device_schema1: device_schema1,
      device_schema2: device_schema2,
      device1: device1,
      device2: device2,
      interface1: interface1,
      interface2: interface2
    }
  end

  describe "cleanup process" do
    test "worker starts successfully" do
      {:ok, pid} = NeighborCleanupWorker.start_link()
      assert Process.alive?(pid)
      GenServer.stop(pid)
    end

    test "cleanup removes stale neighbors across all devices", %{
      device_schema1: device_schema1,
      device_schema2: device_schema2,
      device1: device1,
      device2: device2,
      interface1: interface1,
      interface2: interface2
    } do
      # Create old neighbors on both devices
      two_days_ago = DateTime.add(DateTime.utc_now(), -48, :hour)
      one_hour_ago = DateTime.add(DateTime.utc_now(), -1, :hour)

      # Old neighbor on device1
      {:ok, old_neighbor1} =
        Snmp.upsert_neighbor(%{
          device_id: device_schema1.id,
          interface_id: interface1.id,
          protocol: "lldp",
          remote_chassis_id: "old-neighbor-1",
          remote_system_name: "old-neighbor-1",
          last_discovered_at: two_days_ago
        })

      # Old neighbor on device2
      {:ok, old_neighbor2} =
        Snmp.upsert_neighbor(%{
          device_id: device_schema2.id,
          interface_id: interface2.id,
          protocol: "cdp",
          remote_chassis_id: "old-neighbor-2",
          remote_system_name: "old-neighbor-2",
          last_discovered_at: two_days_ago
        })

      # Recent neighbor on device1
      {:ok, recent_neighbor} =
        Snmp.upsert_neighbor(%{
          device_id: device_schema1.id,
          interface_id: interface1.id,
          protocol: "cdp",
          remote_chassis_id: "recent-neighbor",
          remote_system_name: "recent-neighbor",
          last_discovered_at: one_hour_ago
        })

      # Start worker and trigger cleanup immediately
      {:ok, pid} = NeighborCleanupWorker.start_link()
      send(pid, :cleanup)

      # Wait for cleanup to complete
      Process.sleep(100)

      # Old neighbors should be deleted
      assert Repo.get(Neighbor, old_neighbor1.id) == nil
      assert Repo.get(Neighbor, old_neighbor2.id) == nil

      # Recent neighbor should still exist
      assert Repo.get(Neighbor, recent_neighbor.id)

      GenServer.stop(pid)
    end

    test "cleanup handles device with no neighbors gracefully", %{device1: device1} do
      # Ensure no neighbors exist
      assert Snmp.list_neighbors(device1.id) == []

      {:ok, pid} = NeighborCleanupWorker.start_link()
      send(pid, :cleanup)

      # Should not crash
      Process.sleep(100)
      assert Process.alive?(pid)

      GenServer.stop(pid)
    end

    test "cleanup preserves neighbors within 24 hour threshold", %{
      device_schema1: device_schema1,
      device1: device1,
      interface1: interface1
    } do
      # Create neighbors at various ages
      now = DateTime.utc_now()
      twenty_three_hours_ago = DateTime.add(now, -23, :hour)
      twenty_five_hours_ago = DateTime.add(now, -25, :hour)

      # Neighbor just within threshold
      {:ok, recent_neighbor} =
        Snmp.upsert_neighbor(%{
          device_id: device_schema1.id,
          interface_id: interface1.id,
          protocol: "lldp",
          remote_chassis_id: "recent",
          remote_system_name: "recent",
          last_discovered_at: twenty_three_hours_ago
        })

      # Neighbor just outside threshold
      {:ok, stale_neighbor} =
        Snmp.upsert_neighbor(%{
          device_id: device_schema1.id,
          interface_id: interface1.id,
          protocol: "cdp",
          remote_chassis_id: "stale",
          remote_system_name: "stale",
          last_discovered_at: twenty_five_hours_ago
        })

      {:ok, pid} = NeighborCleanupWorker.start_link()
      send(pid, :cleanup)

      Process.sleep(100)

      # Recent neighbor should still exist
      assert Repo.get(Neighbor, recent_neighbor.id)

      # Stale neighbor should be deleted
      assert Repo.get(Neighbor, stale_neighbor.id) == nil

      GenServer.stop(pid)
    end

    test "cleanup does not affect device without SNMP enabled" do
      user = user_fixture()
      {:ok, org} = Towerops.Organizations.create_organization(%{name: "Test Org 2"}, user.id)

      {:ok, site} =
        Towerops.Sites.create_site(%{
          name: "Test Site 2",
          organization_id: org.id
        })

      # Create device without SNMP enabled
      {:ok, device_schema} =
        Towerops.Devices.create_device(%{
          name: "No SNMP Device",
          ip_address: "192.168.1.100",
          snmp_enabled: false,
          site_id: site.id
        })

      device =
        %Device{}
        |> Device.changeset(%{
          device_id: device_schema.id,
          sys_name: "no-snmp-device",
          sys_descr: "No SNMP Device"
        })
        |> Repo.insert!()

      interface =
        %Interface{}
        |> Interface.changeset(%{
          snmp_device_id: device.id,
          if_index: 1,
          if_descr: "eth0",
          if_type: 6
        })
        |> Repo.insert!()

      # Create old neighbor
      two_days_ago = DateTime.add(DateTime.utc_now(), -48, :hour)

      {:ok, neighbor} =
        Snmp.upsert_neighbor(%{
          device_id: device_schema.id,
          interface_id: interface.id,
          protocol: "lldp",
          remote_chassis_id: "neighbor",
          remote_system_name: "neighbor",
          last_discovered_at: two_days_ago
        })

      {:ok, pid} = NeighborCleanupWorker.start_link()
      send(pid, :cleanup)

      Process.sleep(100)

      # Neighbor should still exist (device not included in cleanup)
      # because cleanup only processes SNMP-enabled devices
      assert Repo.get(Neighbor, neighbor.id)

      GenServer.stop(pid)
    end
  end

  describe "scheduled cleanup" do
    test "worker schedules periodic cleanup" do
      {:ok, pid} = NeighborCleanupWorker.start_link()

      # Check that worker is alive and has scheduled a cleanup message
      assert Process.alive?(pid)

      # Get process info
      {:messages, _messages} = Process.info(pid, :messages)

      # Should eventually have a :cleanup message scheduled
      # (may take a moment for the initial schedule)
      Process.sleep(20)

      GenServer.stop(pid)
    end
  end
end
