defmodule Symbiont.TestHelpers do
  @moduledoc "Shared helpers for Symbiont ExUnit tests."

  @doc "Stop a named process safely — no crash if already dead."
  def safe_stop(name) do
    case Process.whereis(name) do
      nil -> :ok
      pid ->
        try do
          GenServer.stop(pid)
        catch
          :exit, _ -> :ok
        end
    end
  end

  @doc "Stop all standard Symbiont services safely."
  def stop_all_services do
    for name <- [Symbiont.Heartbeat, Symbiont.Queue, Symbiont.Ledger] do
      safe_stop(name)
    end

    :ok
  end

  @doc "Ensure TaskSupervisor is running (needed by Heartbeat)."
  def ensure_task_supervisor do
    unless Process.whereis(Symbiont.TaskSupervisor) do
      Task.Supervisor.start_link(name: Symbiont.TaskSupervisor)
    end
  end
end
