from typing import Generator
from fastapi import Depends
from fastapi.security import OAuth2PasswordBearer
from jose import jwt, JWTError
from sqlalchemy.orm import Session
from app.core import security
from app.core.exceptions import UnauthorizedException, ForbiddenException
from app.db.session import get_db
from app.models.user import User
from app.repositories.user import user_repository
from app.schemas.token import TokenPayload

oauth2_scheme = OAuth2PasswordBearer(
    tokenUrl=f"{security.settings.API_V1_STR}/auth/login"
)

def get_current_user(
    db: Session = Depends(get_db),
    token: str = Depends(oauth2_scheme)
) -> User:
    """FastAPI dependency to extract and validate JWT token from request header, returning User."""
    try:
        payload = jwt.decode(
            token,
            security.settings.SECRET_KEY,
            algorithms=[security.ALGORITHM]
        )
        user_id: str = payload.get("sub")
        token_type: str = payload.get("type")
        
        if user_id is None or token_type != "access":
            raise UnauthorizedException("Invalid token payload.")
            
        token_payload = TokenPayload(sub=user_id, type=token_type)
    except JWTError:
        raise UnauthorizedException("Could not validate credentials.")

    user = user_repository.get(db, id=token_payload.sub)
    if not user:
        raise UnauthorizedException("User not found.")
    if not user.is_active:
        raise UnauthorizedException("Inactive user.")
        
    return user

def get_current_active_superuser(
    current_user: User = Depends(get_current_user),
) -> User:
    """FastAPI dependency to restrict endpoints to admin users only."""
    if not current_user.is_superuser:
        raise ForbiddenException("The user does not have enough privileges.")
    return current_user
