from __future__ import annotations

from fastapi import Depends
from fastapi.security import OAuth2PasswordBearer
from sqlmodel import Session, select

from src.database import engine
from src.models import User
from src.services.auth import decode_jwt

from .http_exceptions import credentials_exception


def get_db():
    with Session(engine) as session:
        yield session


oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/auth/sign-in")


def get_current_user(
    db: Session = Depends(get_db), token: str = Depends(oauth2_scheme)
):
    token_data = decode_jwt(token)
    if token_data is None or token_data.email is None:
        raise credentials_exception

    stmt = select(User).where(User.email == token_data.email)

    user = db.exec(stmt).first()

    if user is None:
        raise credentials_exception

    return user

fastapi.security.OAuth2PasswordBearer src.services.auth.decode_jwt sqlmodel.Session fastapi.Depends sqlmodel.select
[((398, 444), 'fastapi.security.OAuth2PasswordBearer', 'OAuth2PasswordBearer', ([], {'tokenUrl': '"""/auth/sign-in"""'}), "(tokenUrl='/auth/sign-in')\n", (418, 444), False, 'from fastapi.security import OAuth2PasswordBearer\n'), ((487, 502), 'fastapi.Depends', 'Depends', (['get_db'], {}), '(get_db)\n', (494, 502), False, 'from fastapi import Depends\n'), ((517, 539), 'fastapi.Depends', 'Depends', (['oauth2_scheme'], {}), '(oauth2_scheme)\n', (524, 539), False, 'from fastapi import Depends\n'), ((560, 577), 'src.services.auth.decode_jwt', 'decode_jwt', (['token'], {}), '(token)\n', (570, 577), False, 'from src.services.auth import decode_jwt\n'), ((330, 345), 'sqlmodel.Session', 'Session', (['engine'], {}), '(engine)\n', (337, 345), False, 'from sqlmodel import Session, select\n'), ((681, 693), 'sqlmodel.select', 'select', (['User'], {}), '(User)\n', (687, 693), False, 'from sqlmodel import Session, select\n')]