import 'package:flutter/foundation.dart';
import '../network/api_client.dart';
import '../../features/coupons/data/models/coupon_model.dart';
import '../../features/coupons/data/models/holdings_summary_model.dart';

/// 券 API 服务
class CouponApiService {
  final ApiClient _apiClient;

  CouponApiService({ApiClient? apiClient})
      : _apiClient = apiClient ?? ApiClient.instance;

  /// 获取精选/上架券列表（首页用）
  Future<List<CouponModel>> getFeaturedCoupons({int page = 1, int limit = 10}) async {
    try {
      final response = await _apiClient.get(
        '/api/v1/coupons',
        queryParameters: {'page': page, 'limit': limit, 'status': 'listed'},
      );
      final data = response.data is Map<String, dynamic> ? response.data : {};
      final inner = data['data'] ?? data;
      final items = (inner['items'] as List?)
              ?.map((e) => CouponModel.fromJson(e as Map<String, dynamic>))
              .toList() ??
          [];
      return items;
    } catch (e) {
      debugPrint('[CouponApiService] getFeaturedCoupons 失败: $e');
      rethrow;
    }
  }

  /// 获取我的持仓列表
  Future<({List<CouponModel> items, int total})> getMyHoldings({
    int page = 1,
    int limit = 20,
    String? status,
  }) async {
    try {
      final queryParams = <String, dynamic>{'page': page, 'limit': limit};
      if (status != null) queryParams['status'] = status;

      final response = await _apiClient.get(
        '/api/v1/coupons/my',
        queryParameters: queryParams,
      );
      final data = response.data is Map<String, dynamic> ? response.data : {};
      final inner = data['data'] ?? data;
      final items = (inner['items'] as List?)
              ?.map((e) => CouponModel.fromJson(e as Map<String, dynamic>))
              .toList() ??
          [];
      return (items: items, total: (inner['total'] as int?) ?? items.length);
    } catch (e) {
      debugPrint('[CouponApiService] getMyHoldings 失败: $e');
      rethrow;
    }
  }

  /// 获取持仓汇总
  Future<HoldingsSummaryModel> getHoldingsSummary() async {
    try {
      final response = await _apiClient.get('/api/v1/coupons/my/summary');
      final data = response.data is Map<String, dynamic> ? response.data : {};
      final inner = data['data'] ?? data;
      return HoldingsSummaryModel.fromJson(inner as Map<String, dynamic>);
    } catch (e) {
      debugPrint('[CouponApiService] getHoldingsSummary 失败: $e');
      rethrow;
    }
  }

  /// 获取券详情
  Future<CouponModel> getCouponDetail(String id) async {
    try {
      final response = await _apiClient.get('/api/v1/coupons/$id');
      final data = response.data is Map<String, dynamic> ? response.data : {};
      final inner = data['data'] ?? data;
      return CouponModel.fromJson(inner as Map<String, dynamic>);
    } catch (e) {
      debugPrint('[CouponApiService] getCouponDetail 失败: $e');
      rethrow;
    }
  }
}
