defmodule Aprsme.SignalHandlerTest do
  use ExUnit.Case, async: true

  alias Aprsme.SignalHandler

  describe "handle_info/2" do
    test "ignores unrecognized messages without changing state" do
      state = %{some: :state}
      assert SignalHandler.handle_info(:random, state) == {:noreply, state}
      assert SignalHandler.handle_info({:other, "msg"}, state) == {:noreply, state}
    end

    test "sigterm branch spawn_links a shutdown task without crashing the caller" do
      # Trap exits so the spawn_link from handle_info doesn't bring the test down.
      Process.flag(:trap_exit, true)

      assert {:noreply, :state_x} =
               SignalHandler.handle_info({:signal, :sigterm}, :state_x)

      # Drain any :EXIT messages from the spawned task.
      receive do
        {:EXIT, _pid, _reason} -> :ok
      after
        200 -> :ok
      end

      # The spawned task calls the real ShutdownHandler.shutdown() if the process
      # is running. Reset its state so other tests aren't affected.
      if pid = Process.whereis(Aprsme.ShutdownHandler) do
        :sys.replace_state(pid, fn state -> %{state | shutting_down: false} end)
        Application.put_env(:aprsme, :health_status, :healthy)
      end
    end
  end

  describe "init/1" do
    test "installs a SIGTERM handler and returns an empty state" do
      # :os.set_signal is process-global but calling it a second time with
      # :handle is idempotent at the VM level. Safe to exercise.
      assert {:ok, %{}} = SignalHandler.init([])
    end
  end
end
