# -*- coding: utf-8 -*-
from __future__ import annotations

import logging

from django.contrib import auth
from django.core.exceptions import ImproperlyConfigured
from django.http import HttpRequest
from django.utils.deprecation import MiddlewareMixin

from hotpocket_backend.apps.accounts.models import AccessToken, Account

LOGGER = logging.getLogger(__name__)


class AccessTokenMiddleware(MiddlewareMixin):
    def process_request(self, request: HttpRequest):
        if not hasattr(request, 'user'):
            raise ImproperlyConfigured('No `AuthenticationMiddleware`?')

        authorization_header = request.headers.get('Authorization', None)
        if authorization_header is None:
            return

        try:
            scheme, authorization = authorization_header.split(' ', maxsplit=1)
            assert scheme == 'Bearer', (
                f'Unsupported authorization scheme: `{scheme}`'
            )

            access_token = AccessToken.active_objects.get(key=authorization)
        except (ValueError, AssertionError, AccessToken.DoesNotExist, Account.DoesNotExist) as exception:
            LOGGER.error(
                'Unhandled exception in AccessToken middleware: %s',
                exception,
                exc_info=exception,
            )
            return

        account = auth.authenticate(request, access_token=access_token)
        if account:
            request.user = account
