import 'package:flutter_riverpod/flutter_riverpod.dart';

import '../core/network/dio_client.dart';
import '../data/services/spot_service.dart';

/// 交易对精度配置（来自 spot/v1/config/symbol/list 的 pricePre/volumePre）
class SpotSymbolPrecision {
  final String symbol;   // 如 BTCUSDT
  final int pricePre;    // 价格小数位
  final int volumePre;   // 数量小数位

  const SpotSymbolPrecision({
    required this.symbol,
    this.pricePre = 2,
    this.volumePre = 4,
  });

  factory SpotSymbolPrecision.fromJson(Map<String, dynamic> json) {
    final symbol = (json['symbol'] as String? ?? '').toUpperCase();
    return SpotSymbolPrecision(
      symbol: symbol,
      pricePre: (json['pricePre'] as num?)?.toInt() ?? 2,
      volumePre: (json['volumePre'] as num?)?.toInt() ?? 4,
    );
  }
}

/// 全局现货交易对精度缓存 — 键为大写 symbol（如 "BTCUSDT"）
class SpotSymbolCacheNotifier
    extends Notifier<Map<String, SpotSymbolPrecision>> {
  @override
  Map<String, SpotSymbolPrecision> build() {
    Future.microtask(_load);
    return {};
  }

  Future<void> _load() async {
    try {
      final dio = ref.read(dioClientProvider);
      final list = await SpotService(dio).getSymbols();
      final map = <String, SpotSymbolPrecision>{};
      for (final json in list) {
        final p = SpotSymbolPrecision.fromJson(json);
        if (p.symbol.isNotEmpty) map[p.symbol] = p;
      }
      state = map;
    } catch (_) {}
  }

  Future<void> refresh() => _load();
}

final spotSymbolCacheProvider =
    NotifierProvider<SpotSymbolCacheNotifier, Map<String, SpotSymbolPrecision>>(
  SpotSymbolCacheNotifier.new,
);
