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

import logging

from bthlabs_jsonrpc_core import register_method
from django import db
from django.http import HttpRequest

from hotpocket_soa.dto.accounts import AccessTokenMetaUpdateIn
from hotpocket_soa.services import AccessTokensService

LOGGER = logging.getLogger(__name__)


@register_method('accounts.auth.check', namespace='accounts')
def check(request: HttpRequest) -> bool:
    return request.user.is_anonymous is False


@register_method('accounts.auth.check_access_token', namespace='accounts')
def check_access_token(request: HttpRequest,
                       access_token: str,
                       meta: dict | None = None,
                       ) -> bool:
    assert request.user.is_anonymous is False, 'Not authenticated'

    result = True

    try:
        access_tokens_service = AccessTokensService()

        with db.transaction.atomic():
            access_token_object = access_tokens_service.get_by_key(
                account_uuid=request.user.pk,
                key=access_token,
            )

            meta_update = AccessTokenMetaUpdateIn.model_validate(
                (meta or {}),
            )

            _ = access_tokens_service.update_meta(
                access_token=access_token_object,
                update=meta_update,
            )
    except AccessTokensService.NotFound as exception:
        LOGGER.error(
            'Access Token not found: account_uuid=`%s` key=`%s`',
            request.user.pk,
            access_token,
            exc_info=exception,
        )
        result = False
    except AccessTokensService.AccessDenied as exception:
        LOGGER.error(
            'Access Token access denied: account_uuid=`%s` key=`%s`',
            request.user.pk,
            access_token,
            exc_info=exception,
        )
        result = False

    return result
