defmodule BerrypodWeb.LiveSandboxHook do
  @moduledoc """
  On-mount hook that allows LiveView processes to use the Ecto SQL sandbox.
  Only active in test environment.
  """

  import Phoenix.LiveView
  import Phoenix.Component

  def on_mount(:default, _params, _session, socket) do
    socket =
      assign_new(socket, :phoenix_ecto_sandbox, fn ->
        if connected?(socket), do: get_connect_info(socket, :user_agent)
      end)

    metadata = socket.assigns.phoenix_ecto_sandbox

    if metadata do
      Phoenix.Ecto.SQL.Sandbox.allow(metadata, Ecto.Adapters.SQL.Sandbox)
    end

    {:cont, socket}
  end
end
