from abc import ABC, abstractmethod

from edpauthorization.dto import AuthorizationPrincipal, AuthorizationRequest


class AuthorizationService(ABC):
    @abstractmethod
    def _is_authorized(self, principal: AuthorizationPrincipal, request: AuthorizationRequest) -> bool:
        raise NotImplementedError()

    def _are_authorized(self, principal: AuthorizationPrincipal, requests: list[AuthorizationRequest]) -> bool:
        for request in requests:
            if not self.is_authorized(principal=principal, request=request):
                return False
        return True

    def is_authorized(self, principal: AuthorizationPrincipal, request: AuthorizationRequest) -> bool:
        try:
            return self._is_authorized(principal, request)
        except Exception as ex:
            return self.handle_exception_is_allowed(ex)

    def are_authorized(self, principal: AuthorizationPrincipal, requests: list[AuthorizationRequest]) -> bool:
        try:
            return self._are_authorized(principal, requests)
        except Exception as ex:
            return self.handle_exception_is_allowed(ex)

    def handle_exception_is_allowed(self, exception: Exception) -> bool:
        raise exception
