from core.logger import DBLogger
from data.abc.data_seeder_abc import DataSeederABC
from data.schemas.administration.user_dao import userDao
from data.schemas.permission.permission_dao import permissionDao
from data.schemas.permission.role import Role
from data.schemas.permission.role_dao import roleDao
from data.schemas.permission.role_permission import RolePermission
from data.schemas.permission.role_permission_dao import rolePermissionDao
from data.schemas.permission.role_user import RoleUser
from data.schemas.permission.role_user_dao import roleUserDao

logger = DBLogger(__name__)


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

    async def seed(self):
        logger.info("Creating admin role")
        roles = await roleDao.get_all()
        if len(roles) == 0:
            rid = await roleDao.create(Role(0, "admin", "Default admin role"))
            permissions = await permissionDao.get_all()

            await rolePermissionDao.create_many(
                [RolePermission(0, rid, permission.id) for permission in permissions]
            )

        role = await roleDao.get_by_name("admin")
        if len(await role.users) > 0:
            return

        users = await userDao.get_all()
        if len(users) == 0:
            return

        user = users[0]
        logger.warning(f"Assigning admin role to first user {user.id}")
        await roleUserDao.create(RoleUser(0, role.id, user.id))
