import 'package:dio/dio.dart';

class ApiError implements Exception {
  ApiError({required this.code, required this.message, required this.status});

  final String code;
  final String message;
  final int status;

  factory ApiError.fromDio(DioException e) {
    if (e.type == DioExceptionType.connectionError ||
        e.type == DioExceptionType.connectionTimeout) {
      return ApiError(code: 'connection_refused', message: 'Connection refused', status: 0);
    }
    final response = e.response;
    final data = response?.data;
    if (data is Map<String, dynamic>) {
      final field = data['error'];
      if (field is String) {
        return ApiError(code: field, message: field, status: response?.statusCode ?? 0);
      }
      if (field is Map<String, dynamic>) {
        final code = field['code']?.toString() ?? 'unknown';
        final msg  = field['message']?.toString() ?? code;
        return ApiError(code: code, message: msg, status: response?.statusCode ?? 0);
      }
    }
    final status = response?.statusCode ?? 0;
    if (status == 401) return ApiError(code: 'unauthenticated', message: 'unauthenticated', status: status);
    if (status == 404) return ApiError(code: 'not_found',       message: 'not_found',       status: status);
    return ApiError(code: 'unknown', message: e.message ?? 'unknown', status: status);
  }
}
