from api_graphql.service.collection_result import CollectionResult
from api_graphql.service.query_context import QueryContext
from data.schemas.public.group_dao import groupDao
from service.permission.permissions_enum import Permissions


async def group_by_assignment_resolver(ctx: QueryContext) -> bool:
    if not isinstance(ctx.data, CollectionResult):
        return False

    if ctx.has_permission(Permissions.short_urls_by_assignment):
        groups = [await x.group for x in ctx.data.nodes]
        role_ids = {x.id for x in await ctx.user.roles}
        filtered_groups = [
            g.id
            for g in groups
            if g is not None
            and (roles := await groupDao.get_roles(g.id))
            and all(r.id in role_ids for r in roles)
        ]

        ctx.data.nodes = [
            node
            for node in ctx.data.nodes
            if (await node.group) is not None
            and (await node.group).id in filtered_groups
        ]
        return True

    return True
