"""
FastAPI dependencies
"""

from typing import TYPE_CHECKING, Optional
from fastapi import Depends, HTTPException, status
from fastapi.security import HTTPBearer
from utils.security import decode_access_token

if TYPE_CHECKING:
    from models import User

security = HTTPBearer()


async def get_current_user(credentials = Depends(security)):
    """Get current authenticated user"""
    from models import User
    
    token = credentials.credentials
    payload = decode_access_token(token)
    
    if payload is None:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Invalid authentication credentials",
            headers={"WWW-Authenticate": "Bearer"},
        )
    
    username: str = payload.get("sub")
    if username is None:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Invalid authentication credentials"
        )
    
    user = await User.findOne({"username": username})
    if user is None:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="User not found"
        )
    
    if not user.is_active:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="Inactive user"
        )
    
    return user


async def get_current_active_user(current_user = Depends(get_current_user)):
    """Get current active user"""
    return current_user


def require_role(required_role: str):
    """Dependency to require specific role"""
    def role_checker(current_user = Depends(get_current_user)):
        role_hierarchy = {"admin": 3, "librarian": 2, "member": 1}
        
        user_level = role_hierarchy.get(current_user.role, 0)
        required_level = role_hierarchy.get(required_role, 0)
        
        if user_level < required_level:
            raise HTTPException(
                status_code=status.HTTP_403_FORBIDDEN,
                detail=f"Insufficient permissions. Required role: {required_role}"
            )
        
        return current_user
    
    return role_checker
