import 'dart:developer' as developer;

import 'package:flutter/foundation.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

import '../core/config/app_config.dart';
import '../core/network/spot_ws_client.dart';
import 'profile_provider.dart';

export '../core/network/spot_ws_client.dart' show SpotWsState;

/// 现货 WS 单例；uid 用于用户推送。
final spotWsClientProvider = Provider<SpotWsClient>((ref) {
  final uid = ref.watch(
    profileProvider.select((s) => s.user.uid),
  );

  if (!kReleaseMode) {
    debugPrint('[SpotWsProvider] url=${AppConfig.effectiveWsSpotUrl}');
    developer.log(
      'SpotWsClient init url=${AppConfig.effectiveWsSpotUrl}',
      name: 'SpotWsProvider',
    );
  }

  final client = SpotWsClient(
    wsSpotUrl: AppConfig.effectiveWsSpotUrl,
    uid: uid.isNotEmpty ? uid : null,
  );

  ref.onDispose(client.dispose);
  return client;
});

final spotWsConnectionStateProvider = StreamProvider<SpotWsState>((ref) {
  return ref.watch(spotWsClientProvider).connectionStream;
});
