import 'package:flutter/foundation.dart';
import '../network/api_client.dart';

/// 发行商分析服务（用户画像等）
class IssuerAnalyticsService {
  final ApiClient _apiClient;

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

  /// 获取用户概览
  Future<Map<String, dynamic>> getUserOverview() async {
    try {
      final response = await _apiClient.get('/api/v1/issuers/me/analytics/users');
      final data = response.data is Map<String, dynamic> ? response.data : {};
      return (data['data'] ?? data) as Map<String, dynamic>;
    } catch (e) {
      debugPrint('[IssuerAnalyticsService] getUserOverview 失败: $e');
      rethrow;
    }
  }

  /// 获取人口统计
  Future<Map<String, dynamic>> getDemographics() async {
    try {
      final response = await _apiClient.get('/api/v1/issuers/me/analytics/demographics');
      final data = response.data is Map<String, dynamic> ? response.data : {};
      return (data['data'] ?? data) as Map<String, dynamic>;
    } catch (e) {
      debugPrint('[IssuerAnalyticsService] getDemographics 失败: $e');
      rethrow;
    }
  }

  /// 获取复购分析
  Future<Map<String, dynamic>> getRepurchaseAnalysis() async {
    try {
      final response = await _apiClient.get('/api/v1/issuers/me/analytics/repurchase');
      final data = response.data is Map<String, dynamic> ? response.data : {};
      return (data['data'] ?? data) as Map<String, dynamic>;
    } catch (e) {
      debugPrint('[IssuerAnalyticsService] getRepurchaseAnalysis 失败: $e');
      rethrow;
    }
  }

  /// 获取AI洞察
  Future<List<String>> getAiInsights() async {
    try {
      final response = await _apiClient.get('/api/v1/issuers/me/analytics/ai-insights');
      final data = response.data is Map<String, dynamic> ? response.data : {};
      final inner = data['data'] ?? data;
      if (inner is List) return inner.map((e) => e.toString()).toList();
      if (inner is Map && inner['insights'] is List) {
        return (inner['insights'] as List).map((e) => e.toString()).toList();
      }
      return [];
    } catch (e) {
      debugPrint('[IssuerAnalyticsService] getAiInsights 失败: $e');
      rethrow;
    }
  }
}
