import logging
from django.utils.deprecation import MiddlewareMixin
from django.http import JsonResponse
from django.core.exceptions import ValidationError as DjangoValidationError
from rest_framework.exceptions import APIException

logger = logging.getLogger(__name__)


class ErrorHandlingMiddleware(MiddlewareMixin):
    """Custom error handling middleware"""
    
    def process_exception(self, request, exception):
        """Handle exceptions"""
        if isinstance(exception, APIException):
            # DRF exceptions are handled by DRF
            return None
        
        if isinstance(exception, DjangoValidationError):
            return JsonResponse({
                'error': True,
                'message': 'Validation error',
                'data': {'errors': exception.message_dict if hasattr(exception, 'message_dict') else str(exception)},
                'status_code': 400,
            }, status=400)
        
        # Log unexpected errors
        logger.error(f'Unhandled exception: {exception}', exc_info=True)
        
        # Return generic error in production, detailed in development
        from django.conf import settings
        if settings.DEBUG:
            return JsonResponse({
                'error': True,
                'message': str(exception),
                'data': {},
                'status_code': 500,
            }, status=500)
        else:
            return JsonResponse({
                'error': True,
                'message': 'An internal server error occurred',
                'data': {},
                'status_code': 500,
            }, status=500)

