import 'package:dio/dio.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../../core/network/dio_client.dart';
import '../domain/models/referral_info.dart';

class ReferralRepository {
  final Dio _dio;

  ReferralRepository(this._dio);

  Future<ReferralInfo> getMyReferralInfo() async {
    final res = await _dio.get('/api/v1/referral/me');
    return ReferralInfo.fromJson(res.data as Map<String, dynamic>);
  }

  Future<({List<ReferralItem> items, int total})> getMyReferrals({
    int limit = 20,
    int offset = 0,
  }) async {
    final res = await _dio.get(
      '/api/v1/referral/me/referrals',
      queryParameters: {'limit': limit, 'offset': offset},
    );
    final data = res.data as Map<String, dynamic>;
    final items = (data['items'] as List)
        .map((e) => ReferralItem.fromJson(e as Map<String, dynamic>))
        .toList();
    return (items: items, total: data['total'] as int? ?? 0);
  }

  Future<({List<RewardItem> items, int total})> getMyRewards({
    String? status,
    int limit = 20,
    int offset = 0,
  }) async {
    final res = await _dio.get(
      '/api/v1/referral/me/rewards',
      queryParameters: {
        if (status != null) 'status': status,
        'limit': limit,
        'offset': offset,
      },
    );
    final data = res.data as Map<String, dynamic>;
    final items = (data['items'] as List)
        .map((e) => RewardItem.fromJson(e as Map<String, dynamic>))
        .toList();
    return (items: items, total: data['total'] as int? ?? 0);
  }
}

// ── Riverpod provider ────────────────────────────────────────────────────────

final referralRepositoryProvider = Provider<ReferralRepository>((ref) {
  final dio = ref.watch(dioClientProvider);
  return ReferralRepository(dio);
});
