import logging

from edpauthorization.dto import AuthorizationAction
from edpauthorization.exception import NotAuthorizedException
from edpauthorization.registry import set_action_name, set_resource_type
from messageprocessorutil import UuidMessageProcessor

from ._utils import reply_forbidden

logger = logging.getLogger(__name__)


class SecureProcessorAdapter(UuidMessageProcessor):
    def __init__(
        self,
        processor: UuidMessageProcessor,
        resource_type: str | None = None,
        action_name: AuthorizationAction | None = None,
    ):
        super().__init__()
        self.resource_type = resource_type
        self.action_name = action_name

        self.processor = processor

    def parse_data(self, *args, **kwargs):
        set_resource_type(self.resource_type)
        set_action_name(self.action_name)

        return self.processor.parse_data(*args, **kwargs)

    def call_business(self, obj):
        return self.processor.call_business(obj)

    def format_response(self, message_bus, message, event, input_obj, result):
        return self.processor.format_response(message_bus, message, event, input_obj, result)

    def format_exception(self, message_bus, message, event, input_obj, exception):
        if isinstance(exception, NotAuthorizedException):
            reply_forbidden(message_bus=message_bus, message=message)
            return
        self.processor.format_exception(message_bus, message, event, input_obj, exception)

    def format_parse_exception(self, message_bus, message, event, data, exception):
        if isinstance(exception, NotAuthorizedException):
            reply_forbidden(message_bus=message_bus, message=message)
            return
        self.processor.format_parse_exception(message_bus, message, event, data, exception)
