import 'package:dio/dio.dart';
import 'package:logger/logger.dart';
import 'exceptions.dart';
import 'failures.dart';

class ErrorHandler {
  static final Logger _logger = Logger();

  static Failure handleException(dynamic exception) {
    _logger.e('Error occurred', error: exception);

    if (exception is ServerException) {
      return ServerFailure(exception.message);
    } else if (exception is NetworkException) {
      return NetworkFailure(exception.message);
    } else if (exception is CacheException) {
      return CacheFailure(exception.message);
    } else if (exception is AuthException) {
      return AuthFailure(exception.message);
    } else if (exception is WalletException) {
      return WalletFailure(exception.message);
    } else if (exception is BlockchainException) {
      return BlockchainFailure(exception.message);
    } else if (exception is ValidationException) {
      return ValidationFailure(exception.message);
    } else if (exception is StorageException) {
      return StorageFailure(exception.message);
    } else if (exception is DioException) {
      return _handleDioError(exception);
    } else {
      return ServerFailure(exception.toString());
    }
  }

  static Failure _handleDioError(DioException error) {
    switch (error.type) {
      case DioExceptionType.connectionTimeout:
      case DioExceptionType.sendTimeout:
      case DioExceptionType.receiveTimeout:
        return const NetworkFailure('连接超时，请检查网络');
      case DioExceptionType.connectionError:
        return const NetworkFailure('网络连接失败');
      case DioExceptionType.badResponse:
        return _handleBadResponse(error.response?.statusCode);
      case DioExceptionType.cancel:
        return const ServerFailure('请求已取消');
      default:
        return const ServerFailure('未知错误');
    }
  }

  static Failure _handleBadResponse(int? statusCode) {
    switch (statusCode) {
      case 400:
        return const ServerFailure('请求参数错误');
      case 401:
        return const AuthFailure('登录已过期，请重新登录');
      case 403:
        return const AuthFailure('没有权限访问');
      case 404:
        return const ServerFailure('请求的资源不存在');
      case 500:
        return const ServerFailure('服务器内部错误');
      case 502:
        return const ServerFailure('服务器网关错误');
      case 503:
        return const ServerFailure('服务暂不可用');
      default:
        return ServerFailure('服务器错误 ($statusCode)');
    }
  }
}
