import 'package:logger/logger.dart';

/// Helper class for handling errors consistently across the app
class ErrorUtils {
  static final Logger _logger = Logger();

  /// Formats an error into a user-friendly message while logging technical details
  static String getUserFriendlyMessage(
    dynamic error, {
    String defaultMessage = 'An unexpected error occurred',
  }) {
    // Log the actual error for debugging
    _logger.e('Error: $error');

    // Default friendly message
    String friendlyMessage = defaultMessage;

    // Format specific error types
    if (error is EdgeFunctionException) {
      // Already user-friendly from our custom exception
      friendlyMessage = error.message;
      _logger.d('EdgeFunctionException: ${error.code} - ${error.details}');
    } else if (error.toString().contains('SocketException') ||
        error.toString().contains('network')) {
      friendlyMessage =
          'Network connection issue. Please check your internet connection.';
    } else if (error.toString().contains('timeout')) {
      friendlyMessage = 'Request timed out. Please try again later.';
    } else if (error.toString().contains('server_config_error') ||
        error.toString().contains('server configuration')) {
      friendlyMessage =
          'The service is temporarily unavailable due to maintenance.';
    } else if (error.toString().contains('permission')) {
      friendlyMessage =
          'Missing permission. Please check app permissions in settings.';
    }

    return friendlyMessage;
  }

  /// Helper method to determine if an error is a server-side configuration issue
  static bool isServerConfigError(dynamic error) {
    if (error is EdgeFunctionException) {
      return error.code == 'server_config_error';
    }
    return error.toString().contains('server_config_error') ||
        error.toString().contains('environment variables') ||
        error.toString().contains('configuration error');
  }

  /// Helper method to determine if an error is a network-related issue
  static bool isNetworkError(dynamic error) {
    return error.toString().contains('SocketException') ||
        error.toString().contains('network_error') ||
        error.toString().contains('connection');
  }
}

/// Custom exception for edge function errors
class EdgeFunctionException implements Exception {
  final String code;
  final String message;
  final dynamic details;

  EdgeFunctionException({
    required this.code,
    required this.message,
    this.details,
  });

  @override
  String toString() => 'EdgeFunctionException: $message (code: $code)';
}
