"""Request-scoped authentication context helpers."""

from __future__ import annotations

from contextlib import contextmanager
from contextvars import ContextVar, Token
from typing import Iterator


_current_user_id: ContextVar[str | None] = ContextVar("current_user_id", default=None)


def get_current_user_id() -> str | None:
    """Return the current authenticated user id for this request context."""
    return _current_user_id.get()


@contextmanager
def bind_user_id(user_id: str | None) -> Iterator[None]:
    """Temporarily bind a user id to the current async context."""
    token: Token[str | None] = _current_user_id.set(user_id)
    try:
        yield
    finally:
        _current_user_id.reset(token)
