# django_core_micha/auth/permissions.py
from django.conf import settings
from rest_framework import permissions


def _has_role_from_setting(user, setting_name: str, default_roles) -> bool:
    """
    Generic helper: checks if an authenticated user is superuser
    or has profile.role in roles defined by a settings tuple.
    """
    if not user or not user.is_authenticated:
        return False
    if getattr(user, "is_superuser", False):
        return True

    profile = getattr(user, "profile", None)
    role = getattr(profile, "role", None)

    roles = getattr(settings, setting_name, default_roles)
    return role in roles


def has_invite_admin_rights(user) -> bool:
    """
    Uses INVITE_ADMIN_ROLES (default: ('admin', 'supervisor')).
    """
    return _has_role_from_setting(
        user,
        "INVITE_ADMIN_ROLES",
        ("admin", "supervisor"),
    )


def has_access_code_admin_rights(user) -> bool:
    """
    Uses ACCESS_CODE_ADMIN_ROLES.

    Fallback:
      - if ACCESS_CODE_ADMIN_ROLES is not set,
        it reuses INVITE_ADMIN_ROLES (or its default).
    """
    # Wenn ACCESS_CODE_ADMIN_ROLES nicht gesetzt ist,
    # fallen wir auf INVITE_ADMIN_ROLES zurück:
    if hasattr(settings, "ACCESS_CODE_ADMIN_ROLES"):
        default_roles = getattr(settings, "ACCESS_CODE_ADMIN_ROLES")
    else:
        default_roles = getattr(settings, "INVITE_ADMIN_ROLES", ("admin", "supervisor"))

    return _has_role_from_setting(
        user,
        "ACCESS_CODE_ADMIN_ROLES",
        default_roles,
    )


class IsInviteAdminOrSuperuser(permissions.BasePermission):
    """DRF permission for invite-related admin actions."""

    def has_permission(self, request, view):
        return has_invite_admin_rights(getattr(request, "user", None))


class IsAccessCodeAdminOrSuperuser(permissions.BasePermission):
    """DRF permission for access-code admin actions."""

    def has_permission(self, request, view):
        return has_access_code_admin_rights(getattr(request, "user", None))
