defmodule MicrowavepropWeb.LiveStashGuard do
  @moduledoc """
  Tiny wrapper around `LiveStash.stash/1` that swallows the
  `ArgumentError: not a valid match specification` crash LiveStash 0.2.0
  raises under OTP 28.

  The stash is a convenience for state persistence across reconnects;
  a failure is not fatal to the user's session. We log and return the
  socket unchanged instead of letting the LiveView process terminate
  mid-`handle_event`.

  Remove this module and inline `LiveStash.stash/1` calls once the
  upstream match-spec fix lands in the `live_stash` hex package.
  """

  alias Phoenix.LiveView.Socket

  require Logger

  @doc """
  Best-effort wrapper around `LiveStash.stash/1`.

  Returns the (possibly unchanged) socket no matter what the adapter
  raises.
  """
  @spec stash(Socket.t()) :: Socket.t()
  def stash(socket) do
    LiveStash.stash(socket)
  rescue
    e in ArgumentError ->
      # Expected on OTP 28 with LiveStash 0.2.0 — fires on every event
      # that triggers a stash. Log at debug so the cause stays
      # observable without flooding prod logs.
      Logger.debug("LiveStashGuard: stash skipped (#{Exception.message(e)})")
      socket
  end
end
