from chitai.services.user import UserService
from chitai.services.kosync_device import KosyncDeviceService
from litestar.middleware import (
   AbstractAuthenticationMiddleware,
   AuthenticationResult,
   DefineMiddleware
)
from litestar.connection import ASGIConnection
from litestar.exceptions import NotAuthorizedException, PermissionDeniedException
from chitai.config import settings


class KosyncAuthenticationMiddleware(AbstractAuthenticationMiddleware):
    async def authenticate_request(self, connection: ASGIConnection) -> AuthenticationResult:
        """Given a request, parse the header for Base64 encoded basic auth credentials. """

        # retrieve the auth header
        api_key = connection.headers.get("X-AUTH-USER", None)
        if not api_key:
            raise NotAuthorizedException()
    
        try:
            db_session = settings.alchemy_config.provide_session(connection.app.state, connection.scope)
            user_service = UserService(db_session)
            device_service = KosyncDeviceService(db_session)
 
            device = await device_service.get_by_api_key(api_key)
            user = await user_service.get(device.user_id)

            return AuthenticationResult(user=user, auth=None)

        except PermissionDeniedException as exc:
            print(exc)
            raise NotAuthorizedException()
            
        
kosync_api_key_auth = DefineMiddleware(KosyncAuthenticationMiddleware)