from typing import List, Tuple
from abs_auth_rbac_core.rbac.service import RBACService
from abs_auth_rbac_core.models import Users, Permission, UserPermission, RolePermission
from abs_exception_core.exceptions import NotFoundError


def get_permission_resources(actions: List[str], module: str, user: Users, rbac_service: RBACService) -> Tuple[List[str], bool]:
    ids = set()
    is_super_admin = False
    if user and rbac_service:
        try:
            is_super_admin = any(role.name == "super_admin" for role in user.roles)
            if not is_super_admin:
                with rbac_service.db() as session:
                    for action in actions:
                        # User-direct permissions
                        user_perms = (
                            session.query(Permission.resource)
                            .join(UserPermission, UserPermission.permission_uuid == Permission.uuid)
                            .filter(
                                UserPermission.user_uuid == user.uuid,
                                Permission.action == action,
                                Permission.module == module,
                            )
                            .all()
                        )

                        # Role-based permissions
                        role_uuids = [role.uuid for role in user.roles]
                        role_perms = []
                        if role_uuids:
                            role_perms = (
                                session.query(Permission.resource)
                                .join(RolePermission, RolePermission.permission_uuid == Permission.uuid)
                                .filter(
                                    RolePermission.role_uuid.in_(role_uuids),
                                    Permission.action == action,
                                    Permission.module == module,
                                )
                                .all()
                            )

                        for (resource,) in user_perms + role_perms:
                            id_data = resource.split(":")
                            if len(id_data) == 2:
                                ids.add(id_data[1])
                            else:
                                ids.add(id_data[0])
        except NotFoundError:
            raise NotFoundError(f"User with UUID {user.uuid} not found")
    return list(ids), is_super_admin
