// Sans-IO WebSocket contract: message frames, errors, connection trait, and
// dialer trait (plan 4.8).

///|
/// A WebSocket application data frame (UTF-8 text or raw binary).
#derive(Debug, Eq)
pub(all) enum WsMessage {
  /// UTF-8 text frame (`opcode 0x1`).
  Text(String)
  /// Raw binary frame (`opcode 0x2`).
  Binary(Bytes)
}

///|
/// Why a WebSocket dial, send, receive, or close operation failed.
#derive(Debug, Eq)
pub(all) suberror WsError {
  /// Handshake or connection establishment failed.
  ConnectFailed(String)
  /// WebSocket protocol violation or invalid close code / URL.
  Protocol(String)
  /// Peer closed abnormally or after local close with RFC 6455 status `code` and `reason`.
  Closed(code~ : UInt16, reason~ : String)
  /// Underlying socket or platform I/O failure.
  Io(String)
  /// Operation was cancelled by the caller or parent task group.
  Cancelled
}

///|
/// An open bidirectional WebSocket connection.
pub(open) trait WsConn {
  /// Transmit a text or binary WebSocket frame.
  async fn send(Self, WsMessage) -> Unit raise WsError
  /// Receive the next frame, or `None` on a clean peer close.
  async fn recv(Self) -> WsMessage? raise WsError
  /// Initiate a closing handshake with RFC 6455 status `code` and `reason`.
  async fn close(Self, code~ : UInt16, reason~ : String) -> Unit raise WsError
}

///|
/// Opens a WebSocket connection for OpenAPI `101 Switching Protocols`
/// operations. Implement this trait to plug in any platform-specific WebSocket
/// stack (including custom Wasm host functions).
pub(open) trait WebSocketDialer {
  /// Establish a WebSocket connection to `url` (`ws://` or `wss://`) with
  /// optional handshake `headers` and requested sub-`protocols`.
  async fn dial(
    Self,
    url~ : String,
    headers~ : @runtime.Headers,
    protocols~ : Array[String],
  ) -> &WsConn raise WsError
}