from rest_framework.views import exception_handler
from rest_framework.exceptions import APIException
from rest_framework import status


class CustomAPIException(APIException):
    """Custom API Exception"""
    status_code = status.HTTP_400_BAD_REQUEST
    default_detail = 'A server error occurred.'
    default_code = 'error'

    def __init__(self, detail=None, code=None, status_code=None):
        if status_code is not None:
            self.status_code = status_code
        super().__init__(detail, code)


class ValidationError(CustomAPIException):
    """Validation Error Exception"""
    status_code = status.HTTP_400_BAD_REQUEST
    default_detail = 'Validation error occurred.'


class NotFoundError(CustomAPIException):
    """Not Found Error Exception"""
    status_code = status.HTTP_404_NOT_FOUND
    default_detail = 'Resource not found.'


class PermissionDeniedError(CustomAPIException):
    """Permission Denied Error Exception"""
    status_code = status.HTTP_403_FORBIDDEN
    default_detail = 'You do not have permission to perform this action.'


class AuthenticationError(CustomAPIException):
    """Authentication Error Exception"""
    status_code = status.HTTP_401_UNAUTHORIZED
    default_detail = 'Authentication failed.'


def custom_exception_handler(exc, context):
    """Custom exception handler for DRF"""
    response = exception_handler(exc, context)

    if response is not None:
        custom_response_data = {
            'error': True,
            'message': response.data.get('detail', 'An error occurred'),
            'data': response.data if isinstance(response.data, dict) else {'errors': response.data},
            'status_code': response.status_code,
        }
        response.data = custom_response_data

    return response

