# -*- 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_backend.apps.core.rpc import wrap_soa_errors
from hotpocket_soa.services import (
    AccessTokensService,
    AccountsService,
    AuthKeysService,
)

LOGGER = logging.getLogger(__name__)


@register_method('accounts.access_tokens.create', namespace='accounts')
@wrap_soa_errors
def create(request: HttpRequest,
           auth_key: str,
           meta: dict,
           ) -> str:
    with db.transaction.atomic():
        try:
            auth_key_object = AuthKeysService().get_by_key(
                account_uuid=None,
                key=auth_key,
            )
        except AuthKeysService.NotFound as exception:
            LOGGER.error(
                'Unable to issue access token: %s',
                exception,
                exc_info=exception,
            )
            raise

        try:
            account = AccountsService().get(pk=auth_key_object.account_uuid)
        except AccountsService.NotFound as exception:
            LOGGER.error(
                'Unable to issue access token: %s',
                exception,
                exc_info=exception,
            )
            raise

        access_token = AccessTokensService().create(
            account_uuid=account.pk,
            origin=request.META['HTTP_ORIGIN'],
            meta=meta,
        )

        return access_token.key
