Cypher Query using apoc.do.when inside apoc.periodic.iterate does not work as intended?

Hi all,

I am trying to batch delete a series of nodes. This node i am deleting is connected to another node that are connected back to other nodes with the same label. I have a logic that checks if this connected node I am deleteing is connected to any other nodes then I would delete both nodes, if not just delete the main node. I am sorry if my explanations doesnt make sense, my query will explain it better.
This what my query looks like:

MATCH (a1:NodeA)
WHERE a1.id IN $data
// Get nodeB connected to nodeA
OPTIONAL MATCH (b:NodeB)-[:BUILDS]->(a1)
OPTIONAL MATCH (a2:SKU)<-[:BUILDS]-(b)
WHERE a2 <> a1
// Check if nodeB is not connected to any other nodeAs
WITH DISTINCT a1, a2, b
CALL apoc.do.when(
	a2 IS null,
    'WITH a1, b
    DETACH DELETE a1, b',
    
    'WITH a1
    DETACH DELETE a1',
    {a1:a1,a2:a2,b:b}) YIELD value
RETURN value AS data

I am trying to put this query logic into an apoc.periodic.iterate. I have tried it but I kept getting errors or it wouldn't work.
I am doing this because I will be deleting a lot of these nodes in the 10000s range.
Can anyone help me out with this?

Thank you in advance

What error do you see with periodic iterate? I think you should be able to do something like this:

CALL apoc.periodic.iterate(
  "MATCH (a1:NodeA) WHERE a1.id IN $data RETURN a1",
  "OPTIONAL MATCH (b:NodeB)-[:BUILDS]->(a1)
   OPTIONAL MATCH (a2:SKU)<-[:BUILDS]-(b)
   WHERE a2 <> a1
   WITH DISTINCT a1, a2, b
   CALL apoc.do.when(
	a2 IS null,
        'WITH a1, b
         DETACH DELETE a1, b',
       'WITH a1
        DETACH DELETE a1',
    {a1:a1,a2:a2,b:b}) YIELD value
    RETURN value AS data",
  {params: {data: $data}}
);