from contextvars import ContextVar
from typing import Optional, Final

REQUEST_ID_CTX_KEY: Final[str] = "request_id"
USER_ID_CTX_KEY: Final[str] = "user_id"
USERNAME_CTX_KEY: Final[str] = "username"
ROLE_CTX_KEY: Final[str] = "role"

_request_id_ctx_var: ContextVar[Optional[str]] = ContextVar(REQUEST_ID_CTX_KEY, default=None)
_user_id_ctx_var: ContextVar[Optional[str]] = ContextVar(USER_ID_CTX_KEY, default=None)
_username_ctx_var: ContextVar[Optional[str]] = ContextVar(USERNAME_CTX_KEY, default=None)
_role_ctx_var: ContextVar[Optional[str]] = ContextVar(ROLE_CTX_KEY, default=None)


def get_request_id() -> Optional[str]:
    return _request_id_ctx_var.get()


def set_request_id(request_id: str):
    return _request_id_ctx_var.set(request_id)


def reset_request_id(token):
    _request_id_ctx_var.reset(token)

def get_user_id() -> Optional[str]:
    return _user_id_ctx_var.get()

def set_user_id(user_id: str):
    return _user_id_ctx_var.set(user_id)

def get_username() -> Optional[str]:
    return _username_ctx_var.get()

def set_username(username: str):
    return _username_ctx_var.set(username)

def get_role() -> Optional[str]:
    return _role_ctx_var.get()

def set_role(role: str):
    return _role_ctx_var.set(role)
