export function ensureExtensionProperty(bpmnFactory, commandStack, element, propertyName) {
  const commands = []

  const businessObject = element.businessObject

  let extensionElements = businessObject.get('extensionElements')

  if (!extensionElements) {
    extensionElements = bpmnFactory.create(
      'bpmn:ExtensionElements',
      { values: [] },
    )
    extensionElements.parent = businessObject

    commands.push({
      cmd: 'element.updateModdleProperties',
      context: {
        element,
        moddleElement: businessObject,
        properties: { extensionElements },
      },
    })
  }

  let properties = (extensionElements?.values ?? [])[0]

  if (!properties) {
    const parent = extensionElements

    properties = bpmnFactory.create('camunda:Properties', {
      values: [],
    })
    properties.parent = parent

    commands.push({
      cmd: 'element.updateModdleProperties',
      context: {
        element,
        moddleElement: extensionElements,
        properties: {
          values: [...extensionElements.get('values'), properties],
        },
      },
    })
  }

  let property = properties?.values?.find(property => property.name === propertyName)

  if (!property) {
    property = bpmnFactory.create('camunda:Property', { name: propertyName })
    property.parent = properties

    commands.push({
      cmd: 'element.updateModdleProperties',
      context: {
        element,
        moddleElement: properties,
        properties: {
          values: [...properties.get('values'), property],
        },
      },
    })
  }

  commandStack.execute('properties-panel.multi-command-executor', commands)

  return property
}
