import 'package:logger/logger.dart';
import 'package:sigap/src/utils/helpers/error_utils.dart';

/// Utility class for handling and formatting API and service errors
class ErrorHandler {
  static final Logger _logger = Logger();

  /// Format error messages for UI display
  static String getUIErrorMessage(dynamic error) {
    // Log detailed error for debugging
    _logger.e('Original error: $error');

    String message = 'An unknown error occurred';

    if (error is EdgeFunctionException) {
      return error.message; // Already user-friendly
    }

    // Handle specific error types and messages
    if (error.toString().contains('server_config_error') ||
        error.toString().contains('environment variables')) {
      message =
          'The service is temporarily unavailable. Please try again later.';
    } else if (error.toString().contains('network') ||
        error.toString().contains('SocketException') ||
        error.toString().contains('connection')) {
      message =
          'Network connection issue. Please check your internet connection.';
    } else if (error.toString().contains('timeout')) {
      message = 'The operation timed out. Please try again.';
    } else if (error.toString().contains('decode') ||
        error.toString().contains('Body can not be decoded') ||
        error.toString().contains('invalid_request_format')) {
      message = 'There was a problem with the image format. Please try again.';
    } else if (error.toString().contains('Camera initialization failed')) {
      message =
          'Unable to access camera. Please check your camera permissions.';
    }

    return message;
  }

  /// Log error with context information
  static void logError(
    String context,
    dynamic error, [
    StackTrace? stackTrace,
  ]) {
    _logger.e(
      'Error in $context: $error',
      error: error,
      stackTrace: stackTrace,
    );
  }
}
