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

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

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

	INSERT INTO admin.like (
		user_id,
		post_id,
		comment_id,
		value
	) VALUES (
		_user_id,
		NEW.post_id,
		NEW.comment_id,
		NEW.value
	)
	RETURNING id
	INTO NEW.id;

	RETURN NEW;
END
$BODY$;

GRANT EXECUTE ON FUNCTION _api.like_insert()
	TO rest_user;
GRANT INSERT ON TABLE api.like
	TO rest_user;
GRANT INSERT ON TABLE admin.like
	TO rest_user;
GRANT UPDATE ON TABLE sys.like_id_seq
	TO rest_user;

CREATE TRIGGER api_like_insert_trgr
	INSTEAD OF INSERT
			ON api.like
			FOR EACH ROW
				EXECUTE PROCEDURE _api.like_insert();
