CREATE FUNCTION _api.serve_user_or_default_media(
	_user_id INTEGER,
	_type xssbook.user_media_type,
	_default TEXT
)
RETURNS sys."*/*"
LANGUAGE plpgsql VOLATILE
AS $BODY$
DECLARE
	_media_id INTEGER;
BEGIN

	SELECT id
	FROM xssbook.user_media m
	WHERE m.type = _type
	AND m.user_id = _user_id
	INTO _media_id;

	IF FOUND THEN
		RETURN _api.serve_user_media(_media_id);
	END IF;

	SELECT id
	FROM xssbook.media m
	WHERE m.name = _default
	INTO _media_id;

	IF FOUND THEN
		RETURN _api.serve_system_media(_media_id);
	END IF;

	PERFORM _api_raise_not_found();
END
$BODY$;

GRANT EXECUTE ON FUNCTION _api.serve_user_or_default_media(INTEGER, xssbook.user_media_type, TEXT)
	TO rest_anon, rest_user;
GRANT SELECT ON TABLE xssbook.user_media
	TO rest_anon, rest_user;
GRANT SELECT ON TABLE xssbook.media
	TO rest_anon, rest_user;
