import uuid

from core.logger import DBLogger
from data.abc.data_seeder_abc import DataSeederABC
from data.schemas.administration.api_key import ApiKey
from data.schemas.administration.api_key_dao import apiKeyDao
from data.schemas.permission.api_key_permission import ApiKeyPermission
from data.schemas.permission.api_key_permission_dao import apiKeyPermissionDao
from data.schemas.permission.permission_dao import permissionDao

logger = DBLogger(__name__)


class ApiKeySeeder(DataSeederABC):
    def __init__(self):
        DataSeederABC.__init__(self)

    async def seed(self):
        api_keys = await apiKeyDao.get_all()
        if len(api_keys) > 0:
            logger.info("Admin API-Key already created")

            api_key = await apiKeyDao.find_single_by(
                [{ApiKey.id: 1}, {ApiKey.identifier: "admin"}]
            )
            logger.warning(f"API-Key {api_key.identifier}: {api_key.key}")

            return

        api_key = ApiKey(0, "admin", str(uuid.uuid4()))
        ak_id = await apiKeyDao.create(api_key)
        permissions = await permissionDao.get_all()

        await apiKeyPermissionDao.create_many(
            [ApiKeyPermission(0, ak_id, permission.id) for permission in permissions]
        )

        logger.warning(f"Created API-Key {api_key.identifier}: {api_key.key}")
