text: const _ = require('lodash')
  const { serializeError } = require('serialize-error')
  const utils = require('../../utils')
  const apiExtensionTemplate = require('../../../resources/api-extension.json')
  
  const mainLogger = utils.getLogger()
  
  async function ensureApiExtensions(
    ctpClient,
    ctpProjectKey,
    ctpAdyenIntegrationBaseUrl
  ) {
    try {
      const logger = mainLogger.child({
        commercetools_project_key: ctpProjectKey,
      })
      const extensionDraft = JSON.parse(
        _.template(JSON.stringify(apiExtensionTemplate))({
          ctpAdyenIntegrationBaseUrl,
        })
      )
      const existingExtension = await fetchExtensionByKey(
        ctpClient,
        apiExtensionTemplate.key
      )
      if (existingExtension === null) {
        await ctpClient.create(ctpClient.builder.extensions, extensionDraft)
        logger.info(
          'Successfully created an API extension for payment resource type ' +
            `(key=${apiExtensionTemplate.key})`
        )
      } else if (
        !_.isEqual(existingExtension.destination, extensionDraft.destination)
      ) {
        await ctpClient.update(
          ctpClient.builder.extensions,
          existingExtension.id,
          existingExtension.version,
          [
            {
              action: 'changeDestination',
              destination: extensionDraft.destination,
            },
          ]
        )
        logger.info(
          'Successfully updated the API extension for payment resource type ' +
            `(key=${apiExtensionTemplate.key})`
        )
      }
    } catch (err) {
      throw Error(
        `Failed to sync API extension (key=${apiExtensionTemplate.key}). ` +
          `Error: ${JSON.stringify(serializeError(err))}`
      )
    }
  }
  
  async function fetchExtensionByKey(ctpClient, key) {
    try {
      const { body } = await ctpClient.fetchByKey(
        ctpClient.builder.extensions,
        key
      )
      return body
    } catch (err) {
      if (err.statusCode === 404) return null
      throw err
    }
  }
  
  module.exports = {
    ensureApiExtensions,
  }
  