"""GET /me — отдаёт текущего пользователя и его RBAC-scope.

MIRROR of main backend's app/api/v1/me.py — kept in sync manually.
Mounted at /api/v1/me; через Caddy `uri strip_prefix /trade-in` это становится
`/trade-in/api/v1/me` снаружи.

Caddy basic_auth пропускает `X-Authenticated-User: <username>` через
`header_up` в каждом reverse_proxy. Frontend дёргает /me чтобы понять
кому что показывать.
"""

from __future__ import annotations

import logging
from typing import Annotated

from fastapi import APIRouter, Header, HTTPException

from app.core.auth import UserScope, get_user_scope

logger = logging.getLogger(__name__)

router = APIRouter()


@router.get("/me")
async def me(
    x_authenticated_user: Annotated[str | None, Header(alias="X-Authenticated-User")] = None,
) -> UserScope:
    """Return the current user's RBAC scope (role + allowed/deny paths)."""
    if not x_authenticated_user:
        raise HTTPException(
            status_code=401,
            detail="no authenticated user (Caddy basic_auth required)",
        )
    try:
        return get_user_scope(x_authenticated_user)
    except KeyError:
        logger.warning(
            "user %r authenticated via Caddy but missing from roles.yaml",
            x_authenticated_user,
        )
        raise HTTPException(
            status_code=403,
            detail="user not in roles config",
        ) from None
