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

	IF NEW.followee_id IS NULL THEN
		-- for now
		PERFORM _api.raise_deny();
	END IF;

	NEW.value := COALESCE(NEW.value, TRUE);

	INSERT INTO xssbook.follow (
		follower_id,
		followee_id,
		value
	) VALUES (
		_user_id,
		NEW.followee_id,
		NEW.value
	)
	RETURNING id
	INTO NEW.id;

	RETURN NEW;
END
$BODY$;

GRANT EXECUTE ON FUNCTION _api.follow_insert()
	TO rest_user;
GRANT INSERT ON TABLE api.follow
	TO rest_user;
GRANT INSERT ON TABLE xssbook.follow
	TO rest_user;
GRANT UPDATE ON TABLE sys.follow_id_seq
	TO rest_user;

CREATE TRIGGER api_follow_insert_trgr
	INSTEAD OF INSERT
			ON api.follow
			FOR EACH ROW
				EXECUTE PROCEDURE _api.follow_insert();
