CREATE FUNCTION _api.serve_system_media(
	_media_id INTEGER
)
RETURNS sys."*/*"
LANGUAGE plpgsql VOLATILE
AS $BODY$
DECLARE
	_headers TEXT;
	_data BYTEA;
BEGIN
	SELECT FORMAT(
      '[{"Content-Type": "%s"},'
       '{"Content-Disposition": "inline; filename=\"%s\""},'
       '{"Cache-Control": "max-age=259200"}]'
      ,	m.mime, m.name)
	FROM admin.media m
	WHERE m.id = _media_id
	INTO _headers;

	SELECT m.content
	FROM admin.media m
	WHERE m.id = _media_id
	INTO _data;

	IF _data IS NOT NULL THEN
		PERFORM SET_CONFIG('response.headers', _headers, true);
		RETURN(_data);
	ELSE
		PERFORM _api.raise_not_found();
	END IF;
END
$BODY$;

GRANT EXECUTE ON FUNCTION _api.serve_system_media(INTEGER)
	TO rest_anon, rest_user;
GRANT SELECT ON TABLE admin.media
	TO rest_anon, rest_user;
