from typing import Annotated

from fastapi import Depends
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
from sqlmodel import select

from apps.users.models import User
from database import AsyncSessionDep
from shared import exceptions as e
from shared.redis import client as cache

BEARER = HTTPBearer()


async def login(
    session: AsyncSessionDep,
    credentials: Annotated[HTTPAuthorizationCredentials, Depends(BEARER)],
):
    user = await cache.get(credentials.credentials)

    if user is None:
        raise e.UnauthorizedException

    try:
        _, user_id = user.decode().split(':')
    except ValueError:
        raise e.UnauthorizedException from None

    user_model_stmt = select(User).where(User.id == int(user_id))
    user_model = (await session.execute(user_model_stmt)).scalar_one_or_none()

    if user_model is None:
        raise e.UnauthorizedException

    return user_model
