"""
FastAPI 依赖注入工具 — 获取当前用户、角色鉴权
"""

from fastapi import Depends, HTTPException, Request, status
from sqlmodel import Session

from app.db.session import get_session
from app.models.user import User, UserRole


def get_current_user(
    request: Request,
    session: Session = Depends(get_session),
) -> User:
    """从 Session 中取 user_id，查库返回当前用户。

    未登录或用户不存在 / 已停用时抛出 401。
    """
    user_id = request.session.get("user_id")
    if user_id is None:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="请先登录",
        )
    user = session.get(User, user_id)
    if user is None or not user.is_active:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="用户不存在或已被停用",
        )
    return user


def require_role(*allowed_roles: UserRole):
    """返回一个 Depends 依赖，要求当前用户拥有指定的角色之一。

    使用示例:
        @router.get("/admin-only")
        def admin_endpoint(user=Depends(require_role(UserRole.zhipianren))):
            ...

        @router.get("/staff")
        def staff_endpoint(user=Depends(require_role(UserRole.zhipianren, UserRole.zebian))):
            ...
    """

    def check_role(user: User = Depends(get_current_user)) -> User:
        if user.role not in allowed_roles:
            raise HTTPException(
                status_code=status.HTTP_403_FORBIDDEN,
                detail="权限不足，无法执行此操作",
            )
        return user

    return check_role