CREATE OR REPLACE FUNCTION public.fn_reminder_upsert(p_data jsonb)
 RETURNS jsonb
 LANGUAGE plpgsql
AS $function$
DECLARE v_id integer;
BEGIN
  IF (p_data->>'id') IS NOT NULL THEN
    UPDATE public.course_reminder_rules
    SET name          = p_data->>'name',
        target_role   = p_data->>'target_role',
        cron_schedule = p_data->>'cron_schedule',
        template_key  = p_data->>'template_key'
    WHERE id = (p_data->>'id')::integer
    RETURNING id INTO v_id;
  ELSE
    INSERT INTO public.course_reminder_rules (course_id, name, target_role, cron_schedule, template_key)
    VALUES (
      (p_data->>'course_id')::integer,
      p_data->>'name',
      p_data->>'target_role',
      p_data->>'cron_schedule',
      p_data->>'template_key'
    )
    RETURNING id INTO v_id;
  END IF;
  RETURN jsonb_build_object('id', v_id);
END;
$function$
;
