import 'package:flutter/foundation.dart';
import '../../../core/network/api_client.dart';
import '../../../core/network/api_endpoints.dart';
import '../../models/referral_model.dart';

abstract class ReferralRemoteDataSource {
  /// 获取指定用户的团队信息
  Future<ReferralInfoResponse> getTeamInfo({
    required String accountSequence,
  });

  /// 获取指定用户的引荐列表（用于伞下树懒加载）
  Future<DirectReferralsResponse> getUserDirectReferrals({
    required String accountSequence,
    int limit = 100,
    int offset = 0,
  });
}

class ReferralRemoteDataSourceImpl implements ReferralRemoteDataSource {
  final ApiClient client;

  ReferralRemoteDataSourceImpl({required this.client});

  @override
  Future<ReferralInfoResponse> getTeamInfo({
    required String accountSequence,
  }) async {
    try {
      debugPrint('获取团队信息: accountSequence=$accountSequence');
      final response = await client.get(ApiEndpoints.teamInfo(accountSequence));

      if (response.statusCode == 200) {
        final data = response.data as Map<String, dynamic>;
        debugPrint('团队信息获取成功: directReferralCount=${data['directReferralCount']}');
        return ReferralInfoResponse.fromJson(data);
      }

      throw Exception('获取团队信息失败');
    } catch (e) {
      debugPrint('获取团队信息失败: $e');
      rethrow;
    }
  }

  @override
  Future<DirectReferralsResponse> getUserDirectReferrals({
    required String accountSequence,
    int limit = 100,
    int offset = 0,
  }) async {
    try {
      debugPrint('获取用户引荐列表: accountSequence=$accountSequence');
      final response = await client.get(
        ApiEndpoints.teamDirectReferrals(accountSequence),
        queryParameters: {
          'limit': limit,
          'offset': offset,
        },
      );

      if (response.statusCode == 200) {
        final data = response.data as Map<String, dynamic>;
        debugPrint('用户引荐列表获取成功: total=${data['total']}');
        return DirectReferralsResponse.fromJson(data);
      }

      throw Exception('获取用户引荐列表失败');
    } catch (e) {
      debugPrint('获取用户引荐列表失败: $e');
      rethrow;
    }
  }
}
