defmodule ToweropsWeb.AgentSocket do
  @moduledoc """
  WebSocket endpoint for remote agent communication.

  Agents connect to: ws://server/socket/agent/websocket
  Authentication token is sent in the channel join payload.

  Uses binary Protocol Buffers encoding for all messages.
  """

  use Phoenix.Socket

  channel "agent:*", ToweropsWeb.AgentChannel

  @impl true
  @spec connect(map(), Phoenix.Socket.t(), map()) :: {:ok, Phoenix.Socket.t()}
  def connect(_params, socket, _connect_info) do
    # Allow all connections - authentication happens at channel join
    {:ok, socket}
  end

  @impl true
  @spec id(Phoenix.Socket.t()) :: String.t() | nil
  def id(socket) do
    # Return nil before authentication (channel join will set agent_token_id)
    case Map.get(socket.assigns, :agent_token_id) do
      nil -> nil
      agent_token_id -> "agent_socket:#{agent_token_id}"
    end
  end
end
