from typing import Optional

from core.logger import DBLogger
from core.database.abc.db_model_dao_abc import DbModelDaoABC
from data.schemas.administration.api_key import ApiKey

logger = DBLogger(__name__)


class ApiKeyDao(DbModelDaoABC[ApiKey]):

    def __init__(self):
        DbModelDaoABC.__init__(self, __name__, ApiKey, "administration.api_keys")

        self.attribute(ApiKey.identifier, str)
        self.attribute(ApiKey.key, str, "keystring")

    async def get_by_identifier(self, ident: str) -> ApiKey:
        result = await self._db.select_map(
            f"SELECT * FROM {self._table_name} WHERE Identifier = '{ident}'"
        )
        return self.to_object(result[0])

    async def get_by_key(self, key: str) -> ApiKey:
        result = await self._db.select_map(
            f"SELECT * FROM {self._table_name} WHERE Keystring = '{key}'"
        )
        return self.to_object(result[0])

    async def find_by_key(self, key: str) -> Optional[ApiKey]:
        result = await self._db.select_map(
            f"SELECT * FROM {self._table_name} WHERE Keystring = '{key}'"
        )
        if not result or len(result) == 0:
            return None

        return self.to_object(result[0])


apiKeyDao = ApiKeyDao()
