/**
 * Build a save failure message from the API response
 *
 * @param {Object} data API response
 * @return {string} message HTML text describing the failure for display to the user
 */
module.exports = function saveFailureMessage( data ) {
	// In most cases, return the error message from the API directly.
	// Handle a few exceptions where it is unsuitable for end-users
	// (some error messages are seemingly intended for tool developers).

	const code = data && data.errors && data.errors[0] && data.errors[0].code;

	if ( code === 'editconflict' ) {
		return mw.msg( 'mobile-frontend-editor-error-conflict' );
	}

	if ( code === 'readonly' ) {
		return data.errors[0].html + '<br>' + data.errors[0].data.readonlyreason;
	}

	if ( data.errors && data.errors[0] ) {
		return data.errors[0].html;
	}

	// This probably indicates a connection problem and a "fake" response
	// generated by mediawiki.Api. TODO Give a better error message here.
	return '';
};
