from typing import Generator

from fastapi import Depends, HTTPException
from fastapi.security import APIKeyHeader
from sqlalchemy.orm import Session
from starlette import status

from app import crud, models
from app.core import security
from app.db.session import SessionLocal

JWT_TOKEN_PREFIX = "Token"  # noqa: S105


def get_db() -> Generator:
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()


def authrization_heder_token(
    api_key: str = Depends(APIKeyHeader(name="Authorization")),
) -> str:
    try:
        token_prefix, token = api_key.split(" ")
    except ValueError:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="unsupported authorization type",
        )
    if token_prefix != JWT_TOKEN_PREFIX:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="unsupported authorization type",
        )
    return token


async def get_current_user(
    token: str = Depends(authrization_heder_token), db: Session = Depends(get_db)
) -> models.User:
    user_id = security.get_user_id_from_token(token=token)
    user = crud.user.get_user_by_id(db, int(user_id))
    if not user:
        raise HTTPException(status_code=404, detail="User not found")
    return user

[((16, 9, 16, 23), 'app.db.session.SessionLocal', 'SessionLocal', ({}, {}), '()', False, 'from app.db.session import SessionLocal\n'), ((42, 17, 42, 50), 'fastapi.Depends', 'Depends', ({(42, 25, 42, 49): 'authrization_heder_token'}, {}), '(authrization_heder_token)', False, 'from fastapi import Depends, HTTPException\n'), ((42, 66, 42, 81), 'fastapi.Depends', 'Depends', ({(42, 74, 42, 80): 'get_db'}, {}), '(get_db)', False, 'from fastapi import Depends, HTTPException\n'), ((44, 14, 44, 58), 'app.core.security.get_user_id_from_token', 'security.get_user_id_from_token', (), '', False, 'from app.core import security\n'), ((24, 27, 24, 61), 'fastapi.security.APIKeyHeader', 'APIKeyHeader', (), '', False, 'from fastapi.security import APIKeyHeader\n'), ((34, 14, 37, 9), 'fastapi.HTTPException', 'HTTPException', (), '', False, 'from fastapi import Depends, HTTPException\n'), ((47, 14, 47, 69), 'fastapi.HTTPException', 'HTTPException', (), '', False, 'from fastapi import Depends, HTTPException\n'), ((29, 14, 32, 9), 'fastapi.HTTPException', 'HTTPException', (), '', False, 'from fastapi import Depends, HTTPException\n')]