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

import datetime
import logging
import uuid

from django.utils.timezone import now
import uuid6

from hotpocket_backend.apps.accounts.models import AuthKey
from hotpocket_backend.apps.core.conf import settings

LOGGER = logging.getLogger(__name__)


class AuthKeysService:
    class AuthKeysServiceError(Exception):
        pass

    class AuthKeyNotFound(AuthKeysServiceError):
        pass

    class AuthKeyExpired(AuthKeysServiceError):
        pass

    class AuthKeyAccessDenied(AuthKeysServiceError):
        pass

    def create(self, *, account_uuid: uuid.UUID) -> AuthKey:
        key = str(uuid6.uuid7())

        return AuthKey.objects.create(
            account_uuid=account_uuid,
            key=key,
        )

    def get(self, *, pk: uuid.UUID) -> AuthKey:
        try:
            query_set = AuthKey.active_objects

            return query_set.get(pk=pk)
        except AuthKey.DoesNotExist as exception:
            raise self.AuthKeyNotFound(
                f'Auth Key not found: pk=`{pk}`',
            ) from exception

    def get_by_key(self, *, key: str, ttl: int | None = None) -> AuthKey:
        try:
            query_set = AuthKey.active_objects

            result = query_set.get(key=key)

            if ttl is None:
                ttl = settings.AUTH_KEY_TTL

            if ttl > 0:
                if result.created_at < now() - datetime.timedelta(seconds=ttl):
                    raise self.AuthKeyExpired(
                        f'Auth Key expired: pk=`{key}`',
                    )

            if result.consumed_at is not None:
                raise self.AuthKeyExpired(
                    f'Auth Key already consumed: pk=`{key}`',
                )

            return result
        except AuthKey.DoesNotExist as exception:
            raise self.AuthKeyNotFound(
                f'Auth Key not found: key=`{key}`',
            ) from exception
