 
 ------ Suggests, Suggest Followers > Triggers ----------------------------------
 
+-- When I insert a suggest, add me as a suggest follower too.
+create function sg_private.follow_suggest()
+returns trigger as $$
+  insert into sg_public.suggest_follower
+  (suggest_id, user_id, session_id)
+  values
+  (new.id, current_setting('jwt.claims.user_id')::uuid, '???');
+$$ language 'plpgsql';
+comment on function sg_private.follow_suggest()
+  is 'Follow a given suggest';
+create trigger insert_suggest_then_follow
+  after insert on sg_public.suggest
+  for each row execute procedure sg_private.follow_suggest();
+comment on trigger insert_suggest_then_follow on sg_public.suggest
+  is 'Whenever I create a suggest, immediately follow the suggest';
+
+-- When I insert a suggest_follower, automatically set the user_id column.
+create trigger insert_suggest_follower_user_id
+  before insert on sg_public.suggest_follower
+  for each row execute procedure sg_private.insert_user_id_column();
+comment on trigger insert_suggest_follower_user_id on sg_public.suggest_follower
+  is 'Whenever I follow a suggest, autopopulate my `user_id`.';
+
 create trigger update_suggest_modified
   before update on sg_public.suggest
   for each row execute procedure sg_private.update_modified_column();

grant select on table sg_public.suggest to sg_anonymous, sg_user, sg_admin;

-- Insert suggest: any via function.
-- TODO insert, when I insert a suggest, add a suggest_follower too

-- Update suggest: admin.
grant update on table sg_public.suggest to sg_admin;

end;
$$ language 'plpgsql';
comment on function sg_private.update_modified_column()
  is 'Whenever the row changes, update the `modified` column.';

-- When inserting a row, automatically set the user_id field.
create or replace function sg_private.insert_user_id_column()
returns trigger as $$
begin new.user_id = current_setting('jwt.claims.user_id')::uuid;
  return new;
end;
$$ language 'plpgsql';
comment on function sg_private.insert_user_id_column()
  is 'When inserting a row, automatically set the `user_id` field.';



