CREATE OR REPLACE FUNCTION public.fn_schedule_upsert(p_data jsonb)
 RETURNS jsonb
 LANGUAGE plpgsql
AS $function$
DECLARE
  v_id integer := (p_data->>'schedule_id')::integer;
  v_result jsonb;
BEGIN
  IF v_id IS NULL THEN
    INSERT INTO public.session_schedules
      (course_id, title, recurrence, duration_min, participant_roles, create_breakout_rooms, advance_hours, notify_hours_before, created_by)
    VALUES (
      (p_data->>'course_id')::integer,
      p_data->>'title',
      p_data->'recurrence',
      (p_data->>'duration_min')::integer,
      ARRAY(SELECT jsonb_array_elements_text(p_data->'participant_roles')),
      (p_data->>'create_breakout_rooms')::boolean,
      (p_data->>'advance_hours')::integer,
      (p_data->>'notify_hours_before')::integer,
      (p_data->>'created_by')::bigint
    )
    RETURNING jsonb_build_object('schedule_id', schedule_id) INTO v_result;
  ELSE
    UPDATE public.session_schedules SET
      title                 = p_data->>'title',
      recurrence            = p_data->'recurrence',
      duration_min          = (p_data->>'duration_min')::integer,
      participant_roles     = ARRAY(SELECT jsonb_array_elements_text(p_data->'participant_roles')),
      create_breakout_rooms = (p_data->>'create_breakout_rooms')::boolean,
      advance_hours         = (p_data->>'advance_hours')::integer,
      notify_hours_before   = (p_data->>'notify_hours_before')::integer
    WHERE schedule_id = v_id
    RETURNING jsonb_build_object('schedule_id', schedule_id) INTO v_result;
  END IF;
  RETURN v_result;
END;
$function$
;
