defmodule Aprsme.Workers.PacketCleanupWorkerTest do
  use Aprsme.DataCase, async: false

  alias Aprsme.BadPacket
  alias Aprsme.Workers.PacketCleanupWorker

  describe "perform/1 without cleanup_days" do
    test "cleans up expired bad packets" do
      # Create an old bad packet
      retention_days = Application.get_env(:aprsme, :packet_retention_days, 7)

      old_time =
        DateTime.utc_now()
        |> DateTime.add(-(retention_days + 10) * 86_400, :second)
        |> DateTime.truncate(:microsecond)

      Repo.insert!(%BadPacket{raw_packet: "bad", error_message: "test", attempted_at: old_time})

      # Create a recent bad packet
      recent_time =
        DateTime.utc_now()
        |> DateTime.add(-3600, :second)
        |> DateTime.truncate(:microsecond)

      Repo.insert!(%BadPacket{raw_packet: "recent_bad", error_message: "test", attempted_at: recent_time})

      assert :ok = PacketCleanupWorker.perform(%{})

      # Only recent bad packet should remain
      assert Repo.aggregate(BadPacket, :count) == 1
    end
  end

  describe "perform/1 with negative cleanup_days" do
    test "falls through to default perform and succeeds" do
      assert :ok = PacketCleanupWorker.perform(%{"cleanup_days" => -1})
    end
  end

  describe "perform/1 with extra fields that the guard ignores" do
    test "accepts a map with cleanup_days plus unrelated keys" do
      assert :ok =
               PacketCleanupWorker.perform(%{
                 "cleanup_days" => 30,
                 "random_field" => "ignored"
               })
    end

    test "handles zero cleanup_days by falling through to default" do
      assert :ok = PacketCleanupWorker.perform(%{"cleanup_days" => 0})
    end

    test "handles non-integer cleanup_days by falling through to default" do
      assert :ok = PacketCleanupWorker.perform(%{"cleanup_days" => "string"})
    end
  end
end
