import 'dart:typed_data';

import 'package:networks_sdk/src/domain/entities/socket_connection_state.dart';
import 'package:networks_sdk/src/domain/entities/socket_error.dart';
import 'package:networks_sdk/src/presentation/wiring/networks_sdk_wiring.dart';
import 'package:networks_sdk/src/presentation/wiring/socket_config.dart';

/// 实时通信公开接口
///
/// 底层基于 WebSocket，支持 JSON / 字符串 / 二进制消息、
/// 自动重连（含无限重连）、Token 热更新、消息加密/解密钩子。
///
/// ## 使用方式
///
/// ```dart
/// final messaging = NetworksMessagingApi();
/// await messaging.initialize(SocketConfig(...));
///
/// await messaging.connect('wss://api.example.com/ws', token: 'xxx');
///
/// messaging.messageStream.listen((msg) => print(msg));
///
/// await messaging.send({'type': 'chat', 'data': {...}});
///
/// // Token 热更新（不断连）
/// messaging.updateToken('new_token');
///
/// // 发送二进制
/// await messaging.sendBytes(Uint8List.fromList([0x01, 0x02]));
///
/// await messaging.disconnect();
/// await messaging.dispose();
/// ```
abstract class NetworksMessagingApi {
  factory NetworksMessagingApi() => NetworksSdkWiring.buildMessagingApi();

  void initialize(SocketConfig config);

  Future<bool> connect(String url, {String? token});

  Future<void> disconnect();

  bool get isConnected;

  SocketConnectionState get connectionState;

  /// Token 热更新（不断开连接）
  ///
  /// 仅更新内部 token，下次重连自动使用新 token。
  void updateToken(String token);

  Future<bool> send(Map<String, dynamic> message);

  Future<bool> sendString(String message);

  /// 发送二进制数据
  Future<bool> sendBytes(List<int> bytes);

  Stream<Map<String, dynamic>> get messageStream;

  Stream<String> get rawMessageStream;

  /// 二进制消息流
  Stream<Uint8List> get binaryMessageStream;

  Stream<SocketConnectionState> get connectionStateStream;

  Stream<SocketError> get errorStream;

  void onEnterForeground();

  void onEnterBackground();

  Future<void> dispose();
}
