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

/// 发行商信用评分服务
class IssuerCreditService {
  final ApiClient _apiClient;

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

  /// 获取信用评分详情
  Future<CreditModel> getCredit() async {
    try {
      final response = await _apiClient.get('/api/v1/issuers/me/credit');
      final data = response.data is Map<String, dynamic> ? response.data : {};
      final inner = data['data'] ?? data;
      return CreditModel.fromJson(inner as Map<String, dynamic>);
    } catch (e) {
      debugPrint('[IssuerCreditService] getCredit 失败: $e');
      rethrow;
    }
  }
}

class CreditModel {
  final String grade;
  final int score;
  final List<CreditFactor> factors;
  final List<String> tiers;
  final int currentTierIndex;
  final List<String> suggestions;

  const CreditModel({
    required this.grade,
    required this.score,
    required this.factors,
    required this.tiers,
    required this.currentTierIndex,
    required this.suggestions,
  });

  factory CreditModel.fromJson(Map<String, dynamic> json) {
    return CreditModel(
      grade: json['grade'] ?? 'N/A',
      score: json['score'] ?? 0,
      factors: (json['factors'] as List?)
              ?.map((e) => CreditFactor.fromJson(e as Map<String, dynamic>))
              .toList() ??
          [],
      tiers: (json['tiers'] as List?)?.map((e) => e.toString()).toList() ??
          ['Bronze', 'Silver', 'Gold', 'Platinum', 'Diamond'],
      currentTierIndex: json['currentTierIndex'] ?? 0,
      suggestions: (json['suggestions'] as List?)?.map((e) => e.toString()).toList() ?? [],
    );
  }
}

class CreditFactor {
  final String name;
  final double score;
  final double weight;

  const CreditFactor({
    required this.name,
    required this.score,
    required this.weight,
  });

  factory CreditFactor.fromJson(Map<String, dynamic> json) {
    return CreditFactor(
      name: json['name'] ?? '',
      score: (json['score'] is num) ? (json['score'] as num).toDouble() : 0,
      weight: (json['weight'] is num) ? (json['weight'] as num).toDouble() : 0,
    );
  }
}
