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

/// 发行商概况服务
class IssuerService {
  final ApiClient _apiClient;

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

  /// 获取发行商资料
  Future<IssuerProfile> getProfile() async {
    try {
      final response = await _apiClient.get('/api/v1/issuers/me');
      final data = response.data is Map<String, dynamic> ? response.data : {};
      final inner = data['data'] ?? data;
      return IssuerProfile.fromJson(inner as Map<String, dynamic>);
    } catch (e) {
      debugPrint('[IssuerService] getProfile 失败: $e');
      rethrow;
    }
  }

  /// 获取仪表盘统计
  Future<IssuerStats> getStats() async {
    try {
      final response = await _apiClient.get('/api/v1/issuers/me/stats');
      final data = response.data is Map<String, dynamic> ? response.data : {};
      final inner = data['data'] ?? data;
      return IssuerStats.fromJson(inner as Map<String, dynamic>);
    } catch (e) {
      debugPrint('[IssuerService] getStats 失败: $e');
      rethrow;
    }
  }

  /// 更新发行商资料
  Future<void> updateProfile(Map<String, dynamic> updates) async {
    try {
      await _apiClient.put('/api/v1/issuers/me', data: updates);
    } catch (e) {
      debugPrint('[IssuerService] updateProfile 失败: $e');
      rethrow;
    }
  }
}

class IssuerProfile {
  final String id;
  final String companyName;
  final String? logoUrl;
  final String? creditRating;
  final String status;
  final String? contactEmail;
  final String? contactPhone;

  const IssuerProfile({
    required this.id,
    required this.companyName,
    this.logoUrl,
    this.creditRating,
    required this.status,
    this.contactEmail,
    this.contactPhone,
  });

  factory IssuerProfile.fromJson(Map<String, dynamic> json) {
    return IssuerProfile(
      id: json['id'] ?? '',
      companyName: json['companyName'] ?? '',
      logoUrl: json['logoUrl'],
      creditRating: json['creditRating'],
      status: json['status'] ?? '',
      contactEmail: json['contactEmail'],
      contactPhone: json['contactPhone'],
    );
  }
}

class IssuerStats {
  final int issuedCount;
  final double redemptionRate;
  final double totalRevenue;
  final String creditGrade;
  final int creditScore;
  final double quotaUsed;
  final double quotaTotal;

  const IssuerStats({
    required this.issuedCount,
    required this.redemptionRate,
    required this.totalRevenue,
    required this.creditGrade,
    required this.creditScore,
    required this.quotaUsed,
    required this.quotaTotal,
  });

  factory IssuerStats.fromJson(Map<String, dynamic> json) {
    return IssuerStats(
      issuedCount: json['issuedCount'] ?? 0,
      redemptionRate: _toDouble(json['redemptionRate']),
      totalRevenue: _toDouble(json['totalRevenue']),
      creditGrade: json['creditGrade'] ?? 'N/A',
      creditScore: json['creditScore'] ?? 0,
      quotaUsed: _toDouble(json['quotaUsed']),
      quotaTotal: _toDouble(json['quotaTotal']),
    );
  }

  static double _toDouble(dynamic v) {
    if (v == null) return 0;
    if (v is num) return v.toDouble();
    return double.tryParse(v.toString()) ?? 0;
  }
}
