import '../../core/constants/api_endpoints.dart';
import '../../core/network/dio_client.dart';
import '../models/coin.dart';

/// 行情服务
class MarketService {
  final DioClient _client;

  MarketService(this._client);

  /// 获取币种列表
  Future<ApiResponse<List<Coin>>> getCoinList() async {
    final response = await _client.get<Map<String, dynamic>>(
      ApiEndpoints.coinList,
    );

    if (response.success && response.data != null) {
      final list = response.data!['list'] as List?;
      final coins = list?.map((e) => Coin.fromJson(e as Map<String, dynamic>)).toList() ?? [];
      return ApiResponse.success(coins, response.message);
    }
    return ApiResponse.fail(response.message ?? '获取币种列表失败');
  }

  /// 获取币种详情
  Future<ApiResponse<Coin>> getCoinDetail(String code) async {
    final response = await _client.get<Map<String, dynamic>>(
      ApiEndpoints.coinDetail,
      queryParameters: {'code': code},
    );

    if (response.success && response.data != null) {
      return ApiResponse.success(
        Coin.fromJson(response.data!),
        response.message,
      );
    }
    return ApiResponse.fail(response.message ?? '获取币种详情失败');
  }

  /// 搜索币种
  Future<ApiResponse<List<Coin>>> searchCoins(String keyword) async {
    final response = await _client.get<Map<String, dynamic>>(
      ApiEndpoints.coinSearch,
      queryParameters: {'keyword': keyword},
    );

    if (response.success && response.data != null) {
      final list = response.data!['list'] as List?;
      final coins = list?.map((e) => Coin.fromJson(e as Map<String, dynamic>)).toList() ?? [];
      return ApiResponse.success(coins, response.message);
    }
    return ApiResponse.fail(response.message ?? '搜索失败');
  }
}
