If you trace through the steps involved in creating an activity in a Moodle course, they roughly break down into:
- Create a course module instance (a record in mdl_course_modules), to hold the generic details about the activity (section, visibility, etc) - see https://docs.moodle.org/dev/Course_module for more details.
- Call PLUGINNAME_add_instance($formdata, [$formobject]) to set up the specific, internal data of the activity (the data from the form will have the cmid created above as well)
- Adjust the cm record so the 'instance' field points to the return value from PLUGINNAME_add_instance
- Refresh the course cache
You can look through the code in course/modedit.php and try calling the function add_moduleinfo() to do this.