On demand item production

Hi, I am new in erpnext and need some help to create an automatic “on demand” warehouse / production system.

My procedure (triggered by a api call): An item is requested (via material request (removal)). If the Item is in stock everything is fine and the stock will be reduced (return success). If not: An new work order will be created. If the required material (other item) for the work order is not in stock, a material request (purchasing) will be created. In this case the return contains the original material request id and the work order id, in order to fulfill the work oder and complete the original material request. It would also be great if only the original material request can only “consume” the created product (not another on in the meantime).

I searched the internet alot, but nothing worked as wanted. Automatically reordering of an item only triggered on a specific stock level and not on demand. I could programm my procedure, by calling all api enpoints by myselve, but I also want this to work, If I create a material request manually.
Some ideas: automatically create a production plan (dont know how)? use server side scipts (rare examples).

Please share some ideas.

Jonas