defmodule WhoNeedHelp.TrackingPresenceCleanup do
  @moduledoc false

  use GenServer

  alias WhoNeedHelp.Tracking
  alias WhoNeedHelpWeb.Presence

  def start_link(options), do: GenServer.start_link(__MODULE__, options, name: __MODULE__)

  def maybe_stop(key, assignment_id, user_id, tracking_session_id) do
    GenServer.cast(
      __MODULE__,
      {:maybe_stop, key, assignment_id, user_id, tracking_session_id}
    )
  end

  @impl GenServer
  def init(_options), do: {:ok, %{}}

  @impl GenServer
  def handle_cast(
        {:maybe_stop, key, assignment_id, user_id, tracking_session_id},
        state
      ) do
    if Presence.get_by_key(Presence.tracking_topic(), key) == [] do
      Tracking.stop_browser_session(assignment_id, user_id, tracking_session_id)
    end

    {:noreply, state}
  end
end
