"""MFA enforcement policy for privileged roles.

The set of roles that MUST have a verified TOTP MFA device is centralised here
so future toggles touch one constant. Used by ``MFAEnforcementMiddleware``
(`apps/core/middleware.py`) to redirect un-enrolled privileged users to the
enrolment flow on every request.

Policy: privileged users may sign in with email + password, but cannot access
any non-MFA, non-static URL until they have a verified ``MFADevice``.
"""
from __future__ import annotations

from apps.core.permissions.roles import UserRole

# MFA temporarily disabled for testing — re-populate to re-enable enforcement.
PRIVILEGED_ROLES: frozenset[str] = frozenset()


def mfa_required_for(user) -> bool:
    """Return True when this user's role mandates MFA enrolment."""
    if not user or not getattr(user, "is_authenticated", False):
        return False
    return bool(getattr(user, "role", "")) and user.role in PRIVILEGED_ROLES


def has_verified_mfa(user) -> bool:
    """Return True when the user has at least one verified TOTP device."""
    from apps.core.authentication.models import MFADevice

    return (
        MFADevice.objects.filter(
            user=user,
            is_verified=True,
            device_type=MFADevice.DeviceType.TOTP,
        )
        .exclude(secret="")
        .exists()
    )
