from core.logger import DBLogger
from data.schemas.public.group import Group

logger = DBLogger(__name__)

from core.database.abc.db_model_dao_abc import DbModelDaoABC


class GroupDao(DbModelDaoABC[Group]):
    def __init__(self):
        DbModelDaoABC.__init__(self, __name__, Group, "public.groups")
        self.attribute(Group.name, str)

        self.attribute(Group.user_space_id, int)
        self.reference("userspace", "id", Group.user_space_id, "public.user_spaces")

    async def get_by_name(self, name: str) -> Group:
        result = await self._db.select_map(
            f"SELECT * FROM {self._table_name} WHERE Name = '{name}'"
        )
        return self.to_object(result[0])

    async def get_roles(self, group_id: int):
        result = await self._db.select_map(
            f"""
            SELECT r.* 
            FROM permission.roles r
            JOIN public.group_role_assignments gra ON r.id = gra.roleId
            WHERE gra.groupId = {group_id}
            AND gra.deleted = FALSE
            """
        )
        from data.schemas.permission.role_dao import roleDao

        return [roleDao.to_object(x) for x in result]


groupDao = GroupDao()
