"""Permission that is fail-OPEN when unconfigured and fail-CLOSED when configured — matching the
hand-rolled Andrea services (`if SVC_KEY: require it; else: allow`). Pair it with the
ServiceOrOIDCAuthentication auth class: authentication resolves the credential, this permission
decides whether one is REQUIRED for this deployment."""
from django.conf import settings
from rest_framework.permissions import BasePermission


class ServiceKeyRequiredIfConfigured(BasePermission):
    """Require an authenticated principal ONLY when service auth is configured
    (settings.ANDREA_SVC_KEYS or an OIDC issuer). Unconfigured (dev/local) => open, so a service
    behaves exactly like its hand-rolled predecessor did before a key was provisioned."""

    message = "service credential required"

    def has_permission(self, request, view):
        configured = bool(getattr(settings, "ANDREA_SVC_KEYS", None)) or bool(
            getattr(settings, "OIDC_ISSUER", "") and getattr(settings, "OIDC_JWKS_URL", ""))
        if not configured:
            return True
        return bool(getattr(request, "user", None) and request.user.is_authenticated)
