Delete subform rows based on mainform input

Delete subform rows based on mainform input

I took my first adventure in getting ChatGPT to write some code for me this weekend.

I want to ADD new rows, UPDATE existing rows and DELETE existing rows based on the input of a mulitselect lookup in the mainform. ChatGPT produced this for me which seems to work to ADD and UPDATE but then I got into a loop of doom with a very over-confident ChatGPT about whether it's possible to delete rows using script on success or whether I have to call a function to delete. So two questions: 
1. Is this code the best code for ADDING / UPDATING or can someone beat ChatGPT? 
2. what do I do about deleting the rows? Can anyone help me with the on success code / function to call? 

Thanks guys! 

mainRec = Participation[ID == input.ID];
if(mainRec != null)
{
subformRows = Participation_subform[Lookup_to_mainform == mainRec];
for each  selectedValue in mainRec.People_lookup
{
exists = false;
for each  sub in subformRows
{
if(sub.Name_lookup_subform == selectedValue)
{
// Already exists — update values directly
sub.Activity_lookup_subform=input.Activities_lookup;
sub.Service_subform=input.Service;
sub.Time_spent_subform=input.Time_spent;
sub.Date_subform=input.Date_field;
exists = true;
break;
}
}
if(!exists)
{
insert into Participation_subform
[
Lookup_to_mainform=mainRec
Name_lookup_subform=selectedValue
Activity_lookup_subform=input.Activities_lookup
Service_subform=input.Service
Time_spent_subform=input.Time_spent
Date_subform=input.Date_field
Added_User=zoho.loginuser
]
}
}
}