# `ZenWebsocket.SubscriptionManager`
[🔗](https://github.com/ZenHive/zen_websocket/blob/v0.4.2/lib/zen_websocket/subscription_manager.ex#L1)

Manages subscription tracking for WebSocket connections.

Pure functional module - state ownership stays with Client GenServer.
Tracks subscribed channels and provides restoration on reconnect.

## Telemetry Events

The following telemetry events are emitted:

* `[:zen_websocket, :subscription_manager, :add]` - Emitted when a channel is added.
  * Measurements: `%{count: 1}`
  * Metadata: `%{channel: channel}`

* `[:zen_websocket, :subscription_manager, :remove]` - Emitted when a channel is removed.
  * Measurements: `%{count: 1}`
  * Metadata: `%{channel: channel}`

* `[:zen_websocket, :subscription_manager, :restore]` - Emitted when subscriptions are restored.
  * Measurements: `%{channel_count: integer()}`
  * Metadata: `%{channels: [String.t()]}`

## API Functions
| Function | Arity | Description | Param Kinds |
| --- | --- | --- | --- |
| `handle_message` | 2 | Handle incoming subscription confirmation messages. | `msg: value`, `state: value` |
| `build_restore_message` | 1 | Build a restore message for reconnection. | `state: value` |
| `list` | 1 | List all currently tracked subscriptions. | `state: value` |
| `remove` | 2 | Remove a channel from the tracked subscription set. | `state: value`, `channel: value` |
| `add` | 2 | Add a channel to the tracked subscription set. | `state: value`, `channel: value` |

# `state`

```elixir
@type state() :: %{
  :subscriptions =&gt; MapSet.t(String.t()),
  :config =&gt; %{:restore_subscriptions =&gt; boolean(), optional(atom()) =&gt; term()},
  optional(atom()) =&gt; term()
}
```

Client state map containing subscription fields (subset of Client.state)

# `add`

```elixir
@spec add(state(), String.t()) :: state()
```

Adds a channel to the tracked subscription set.

Called when a subscription confirmation is received.

# `build_restore_message`

```elixir
@spec build_restore_message(state()) :: binary() | nil
```

Builds a restore message for reconnection.

Returns nil if:
- No subscriptions to restore
- `restore_subscriptions` config is false

Returns JSON-encoded subscribe message otherwise.

# `handle_message`

```elixir
@spec handle_message(map(), state()) :: state()
```

Handles incoming subscription confirmation messages.

Extracts the channel from the message and adds it to tracked subscriptions.

# `list`

```elixir
@spec list(state()) :: [String.t()]
```

Lists all currently tracked subscriptions.

# `remove`

```elixir
@spec remove(state(), String.t()) :: state()
```

Removes a channel from the tracked subscription set.

Called when unsubscribing from a channel.

---

*Consult [api-reference.md](api-reference.md) for complete listing*
