-- Workflow for Investigator user creation

INSERT INTO workflows (name, trigger_event, definition, is_active)
VALUES ('Investigator Created', 'form.73.updated', '{"conditions":[]}', TRUE)
ON CONFLICT (name) DO NOTHING;

-- Investigator workflow steps
INSERT INTO workflow_steps (workflow_id, step_order, step_type, config) VALUES
  ((SELECT id FROM workflows WHERE name='Investigator Created'),1,'map_fields','{"map":{"user_id":"id"}}'),
  ((SELECT id FROM workflows WHERE name='Investigator Created'),2,'save_record','{"table":"users","data":{"full_name":"{full_name}","password":"{password}"},"context_key":"user_id"}'),
  ((SELECT id FROM workflows WHERE name='Investigator Created'),3,'ensure_group','{"name":"Investigators"}'),
  ((SELECT id FROM workflows WHERE name='Investigator Created'),4,'save_record','{"table":"user_group_memberships","data":{"user_id":"{user_id}","group_id":"{group_id}","role":"Investigator"}}'),
  ((SELECT id FROM workflows WHERE name='Investigator Created'),5,'load_record','{"table":"users","id_key":"user_id","context_key":"user"}'),
  ((SELECT id FROM workflows WHERE name='Investigator Created'),6,'queue_notification','{"entity":"users","record_id":"{user_id}","event_type":"insert","payload":"{user}"}');
