from __future__ import annotations

from collections.abc import Callable

from fastapi import Depends, HTTPException, status

from app.api.dependencies.auth import get_current_user
from app.schemas.auth import AuthenticatedUser


def require_permission(permission_name: str) -> Callable[..., AuthenticatedUser]:
    """Create a dependency that enforces a translated permission flag.

    The flag names intentionally match `PermissionContextRead` fields so
    reviewers can trace permission checks end to end without indirection.
    """

    async def dependency(
        current_user: AuthenticatedUser = Depends(get_current_user),
    ) -> AuthenticatedUser:
        if not hasattr(current_user.permissions, permission_name):
            raise HTTPException(
                status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
                detail=f"Unknown permission flag '{permission_name}'.",
            )

        if not getattr(current_user.permissions, permission_name):
            raise HTTPException(
                status_code=status.HTTP_403_FORBIDDEN,
                detail=f"Missing permission '{permission_name}'.",
            )

        return current_user

    return dependency

