import 'package:dio/dio.dart';
import 'package:injectable/injectable.dart';

import '../../../../../core/constants/api_constants.dart';
import '../../../../../core/network/api_client.dart';
import '../../../../../core/errors/exceptions.dart';
import '../models/p2p_market_stats_model.dart';

abstract class P2PMarketRemoteDataSource {
  Future<P2PMarketStatsModel> getMarketStats();
  Future<List<P2PTopCryptoModel>> getTopCryptos();
  Future<List<P2PMarketHighlightModel>> getMarketHighlights();
}

@Injectable(as: P2PMarketRemoteDataSource)
class P2PMarketRemoteDataSourceImpl implements P2PMarketRemoteDataSource {
  const P2PMarketRemoteDataSourceImpl(this._apiClient);

  final ApiClient _apiClient;

  @override
  Future<P2PMarketStatsModel> getMarketStats() async {
    try {
      final response =
          await _apiClient.get('${ApiConstants.p2pBaseUrl}/market/stats');
      return P2PMarketStatsModel.fromJson(response.data);
    } on DioException catch (e) {
      throw ServerException(
          e.response?.data?['message'] ?? 'Failed to get P2P market stats');
    } catch (e) {
      throw ServerException(e.toString());
    }
  }

  @override
  Future<List<P2PTopCryptoModel>> getTopCryptos() async {
    try {
      final response =
          await _apiClient.get('${ApiConstants.p2pBaseUrl}/market/top');
      return (response.data as List)
          .map((json) => P2PTopCryptoModel.fromJson(json))
          .toList();
    } on DioException catch (e) {
      throw ServerException(
          e.response?.data?['message'] ?? 'Failed to get top cryptocurrencies');
    } catch (e) {
      throw ServerException(e.toString());
    }
  }

  @override
  Future<List<P2PMarketHighlightModel>> getMarketHighlights() async {
    try {
      final response =
          await _apiClient.get('${ApiConstants.p2pBaseUrl}/market/highlight');
      return (response.data as List)
          .map((json) => P2PMarketHighlightModel.fromJson(json))
          .toList();
    } on DioException catch (e) {
      throw ServerException(
          e.response?.data?['message'] ?? 'Failed to get market highlights');
    } catch (e) {
      throw ServerException(e.toString());
    }
  }
}
