function normalizeDocumentFileName(value) {
  const fileName = String(value || '');
  if (!fileName || !/[\u00C2-\u00C5\u00E1\u00E2]/.test(fileName)) return fileName;

  const codePoints = Array.from(fileName, (character) => character.codePointAt(0));
  if (codePoints.some((codePoint) => codePoint > 0xff)) return fileName;

  const legacyBytes = Buffer.from(codePoints);
  const decodedName = legacyBytes.toString('utf8');

  if (
    decodedName.includes('\uFFFD')
    || !Buffer.from(decodedName, 'utf8').equals(legacyBytes)
  ) {
    return fileName;
  }

  return decodedName;
}

module.exports = {
  normalizeDocumentFileName
};
