"""Who the caller is — the two request-scoped resolvers the whole app runs on.

`optional_user` is the EFFECTIVE user (impersonated while a View As is active);
`real_user` is the actually-signed-in one. Both are `(request) -> str | None` so
they work as FastAPI dependencies AND as the identity hooks `bw_admin_api`'s
router expects. Data and permission decisions use `optional_user`; anything that
logs, reports presence, or renders "who you are" uses `real_user`.
"""

from starlette.requests import Request

from app import view_as_policy

SESSION_USER_KEY = "user"


def optional_user(request: Request) -> str | None:
    """The EFFECTIVE username for this request, or None when signed out.

    Runs the view-as re-authorization first (fail-closed: an impersonation that is
    no longer allowed auto-stops here), then returns the impersonated user while a
    View As is active, else the real one."""
    value = request.session.get(SESSION_USER_KEY)
    if not (isinstance(value, str) and value):
        return None
    effective = view_as_policy.verify_and_effective(request)
    return effective.lower() if effective else None


def real_user(request: Request) -> str | None:
    """The actually-signed-in user, for audit lines and View-As controls."""
    value = request.session.get(SESSION_USER_KEY)
    return value.lower() if isinstance(value, str) and value else None
