CREATE FUNCTION api.profile_avatar(
	user_id INTEGER DEFAULT 0
)
RETURNS sys."*/*"
LANGUAGE plpgsql VOLATILE
AS $BODY$
DECLARE
	_id INTEGER;
	_mod INTEGER;
	_name TEXT;
BEGIN
	SELECT media_id INTO _id
	FROM admin.user_media m
	WHERE m.user_id = profile_avatar.user_id
	AND type = 'avatar'::admin.user_media_type;

	-- get default if not exists
	IF NOT FOUND THEN
		_mod = MOD(user_id, 24);
		_name = 'default_avatar_' || _mod || '.png';

		SELECT id INTO _id
		FROM admin.media
		WHERE name = _name;
	END IF;

	RETURN _api.serve_media(_id);
END
$BODY$;

GRANT EXECUTE ON FUNCTION api.profile_avatar(INTEGER)
	TO rest_anon, rest_user;
GRANT SELECT ON TABLE admin.user_media
	TO rest_anon, rest_user;
GRANT SELECT ON TABLE admin.media
	TO rest_anon, rest_user;
