CREATE FUNCTION _api.comment_insert()
RETURNS TRIGGER
LANGUAGE plpgsql VOLATILE
AS $BODY$
DECLARE
	_user_id INTEGER;
BEGIN
	_user_id = _api.get_user_id();

	NEW.content	:= _api.trim(NEW.content);
	PERFORM _api.validate_text(
		_text => NEW.content,
		_column => 'content',
		_min => 1,
		_max => 1024
	);

	PERFORM TRUE
	FROM admin.post
	WHERE id = NEW.post_id;

	IF NOT FOUND THEN
		PERFORM _api.raise(
			_msg => 'api_null_post',
			_err => 400
		);
	END IF;

	INSERT INTO admin.comment (
		user_id,
		post_id,
		content
	) VALUES (
		_user_id,
		NEW.post_id,
		NEW.content
	);

	RETURN NEW;
END
$BODY$;

GRANT EXECUTE ON FUNCTION _api.comment_insert()
	TO rest_user;
GRANT INSERT ON TABLE api.comment
	TO rest_user;
GRANT INSERT ON TABLE admin.comment
	TO rest_user;
GRANT UPDATE ON TABLE sys.comment_id_seq
	TO rest_user;

CREATE TRIGGER api_comment_insert_trgr
	INSTEAD OF INSERT
			ON api.comment
			FOR EACH ROW
				EXECUTE PROCEDURE _api.comment_insert();
