from fastapi import Request, HTTPException, Depends
from models.sql.user import UserModel


def get_current_user(request: Request) -> UserModel:
    """FastAPI dependency: extract authenticated user from request state."""
    user = getattr(request.state, "user", None)
    if not user:
        raise HTTPException(status_code=401, detail="Not authenticated")
    return user


def require_role(*roles: str):
    """FastAPI dependency factory: require user has one of the specified roles."""
    def dependency(request: Request) -> UserModel:
        user = get_current_user(request)
        if user.role not in roles:
            raise HTTPException(status_code=403, detail="Insufficient permissions")
        return user
    return Depends(dependency)


def require_super_admin(request: Request) -> UserModel:
    """FastAPI dependency: require super_admin role."""
    user = get_current_user(request)
    if user.role != "super_admin":
        raise HTTPException(status_code=403, detail="Super admin access required")
    return user


def require_client_admin(request: Request) -> UserModel:
    """FastAPI dependency: require client_admin or super_admin role."""
    user = get_current_user(request)
    if user.role not in ("super_admin", "client_admin"):
        raise HTTPException(status_code=403, detail="Admin access required")
    return user
