from typing import Union

from fastapi import Request
from fastapi.param_functions import Depends, Header
from fastapi.security import OAuth2PasswordBearer
from sqlmodel import Session, select

from ..core.constants import AccessLevel, ContextEnum
from ..core.helpers.database import make_session
from ..core.helpers.exceptions import NotAuthorizedError
from ..core.models import Context, ParsedToken, User
from ..core.security import load_jwt_token

reusable_oauth2 = OAuth2PasswordBearer(tokenUrl="api/v1/auth/access-token")


def get_string_token(token: str = Header(None, alias="Authorization")) -> Union[None, str]:
    if token:
        _, _, token = token.partition(" ")

    return token


def load_access_token(request: Request, token: str = Depends(reusable_oauth2)) -> ParsedToken:
    return load_jwt_token(token)


async def get_current_user(
    session: Session = Depends(make_session), token: ParsedToken = Depends(load_access_token)
) -> User:
    user = session.exec(