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

import logging
import typing

from django.contrib.auth.backends import ModelBackend, UserModel
from django.http import HttpRequest

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

LOGGER = logging.getLogger(__name__)


class AccessTokenBackend(ModelBackend):
    def authenticate(self,
                     request: HttpRequest,
                     access_token: AccessToken | None,
                     ) -> Account | None:
        if not access_token:
            return None

        try:
            user = UserModel.objects.get(pk=access_token.account_uuid)
        except UserModel.DoesNotExist as exception:
            LOGGER.error(
                'Unhandled exception in AccessToken auth: %s',
                exception,
                exc_info=exception,
            )

        if self.user_can_authenticate(user) is False:
            return None

        request.access_token = access_token
        return typing.cast(Account, user)
