/// API 响应状态码
class ResponseCode {
  static const String success = '0000';
  static const String unauthorized = '0002';
}

/// API 响应模型
class ApiResponse<T> {
  final bool success;
  final String? message;
  final T? data;
  final String? code;

  ApiResponse({
    required this.success,
    this.message,
    this.data,
    this.code,
  });

  factory ApiResponse.success(T data, [String? message]) {
    return ApiResponse(
      success: true,
      data: data,
      message: message,
      code: ResponseCode.success,
    );
  }

  factory ApiResponse.fail(String message, [String? code]) {
    return ApiResponse(
      success: false,
      message: message,
      code: code,
    );
  }

  factory ApiResponse.unauthorized(String message) {
    return ApiResponse(
      success: false,
      message: message,
      code: ResponseCode.unauthorized,
    );
  }

  factory ApiResponse.fromJson(
    Map<String, dynamic> json,
    T Function(dynamic)? fromJsonT,
  ) {
    final code = json['code'] as String? ?? '';
    final msg = json['msg'] as String? ?? '';

    return switch (code) {
      ResponseCode.success => _parseSuccess(json, msg, fromJsonT),
      ResponseCode.unauthorized => ApiResponse.unauthorized(msg),
      _ => ApiResponse.fail(msg, code),
    };
  }

  static ApiResponse<T> _parseSuccess<T>(
    Map<String, dynamic> json,
    String msg,
    T Function(dynamic)? fromJsonT,
  ) {
    final data = json['data'];
    if (fromJsonT != null && data != null) {
      return ApiResponse.success(fromJsonT(data), msg);
    }
    return ApiResponse.success(data as T, msg);
  }

  bool get isSuccess => success;
  bool get isUnauthorized => code == ResponseCode.unauthorized;
}
