import '../../models/share_account_model.dart';
import '../../models/mining_record_model.dart';
import '../../models/global_state_model.dart';
import '../../../core/network/api_client.dart';
import '../../../core/network/api_endpoints.dart';
import '../../../core/error/exceptions.dart';

abstract class MiningRemoteDataSource {
  Future<ShareAccountModel> getShareAccount(String accountSequence);
  Future<List<MiningRecordModel>> getMiningRecords(
    String accountSequence, {
    int page = 1,
    int limit = 20,
  });
  Future<GlobalStateModel> getGlobalState();
}

class MiningRemoteDataSourceImpl implements MiningRemoteDataSource {
  final ApiClient client;

  MiningRemoteDataSourceImpl({required this.client});

  @override
  Future<ShareAccountModel> getShareAccount(String accountSequence) async {
    try {
      final response = await client.get(ApiEndpoints.shareAccount(accountSequence));
      return ShareAccountModel.fromJson(response.data);
    } catch (e) {
      throw ServerException(e.toString());
    }
  }

  @override
  Future<List<MiningRecordModel>> getMiningRecords(
    String accountSequence, {
    int page = 1,
    int limit = 20,
  }) async {
    try {
      final response = await client.get(
        ApiEndpoints.miningRecords(accountSequence),
        queryParameters: {'page': page, 'pageSize': limit},
      );
      final items = response.data['items'] as List? ?? [];
      return items.map((json) => MiningRecordModel.fromJson(json)).toList();
    } catch (e) {
      throw ServerException(e.toString());
    }
  }

  @override
  Future<GlobalStateModel> getGlobalState() async {
    try {
      final response = await client.get(ApiEndpoints.globalState);
      return GlobalStateModel.fromJson(response.data);
    } catch (e) {
      throw ServerException(e.toString());
    }
  }
}
