CREATE FUNCTION api.update_user_media(
	media_type admin.user_media_type,
	mime TEXT,
	content TEXT
)
RETURNS void
LANGUAGE plpgsql VOLATILE
AS $BODY$
DECLARE
	_user_id INTEGER;
	_data BYTEA;
BEGIN
	_user_id = _api.get_user_id();
	_data = decode(content, 'base64');

	INSERT INTO admin.user_media (
		user_id,
		content,
		mime,
		type
	) VALUES (
		_user_id,
		_data,
		mime,
		media_type
	) ON CONFLICT (
		"user_id", "type"
	) DO UPDATE SET
		"content" = excluded.content,
		"mime" = excluded.mime,
		"type" = excluded.type,
		"modified" = clock_timestamp();
END
$BODY$;

GRANT EXECUTE ON FUNCTION api.update_user_media(admin.user_media_type, TEXT, TEXT)
	TO rest_user;
GRANT INSERT, UPDATE ON TABLE admin.user_media
	TO rest_user;
GRANT UPDATE ON TABLE sys.user_media_id_seq
	TO rest_user;
