from datetime import datetime
from typing import Optional
from uuid import uuid4

from async_property import async_property

from core.database.abc.db_model_abc import DbModelABC
from core.typing import Id, SerialId
from service.permission.permissions_enum import Permissions


class ApiKey(DbModelABC):
    def __init__(
        self,
        id: SerialId,
        identifier: str,
        key: uuid4,
        deleted: bool = False,
        editor_id: Optional[Id] = None,
        created: Optional[datetime] = None,
        updated: Optional[datetime] = None,
    ):
        DbModelABC.__init__(self, id, deleted, editor_id, created, updated)
        self._identifier = identifier
        self._key = key

    @property
    def identifier(self) -> str:
        return self._identifier

    @property
    def key(self) -> uuid4:
        return self._key

    @async_property
    async def permissions(self):
        from data.schemas.permission.api_key_permission_dao import (
            apiKeyPermissionDao,
        )

        return [
            await x.permission
            for x in await apiKeyPermissionDao.find_by_api_key_id(self.id)
        ]

    async def has_permission(self, permission: Permissions) -> bool:
        return permission.value in [x.name for x in await self.permissions]
