class ChangePrimaryGatewayService {

    public void changePrimaryGatewayMetadata(Stack stack, Optional<String> formerPrimaryGatwayInstanceId, String newPrimaryGatewayInstanceId) {
        if (formerPrimaryGatwayInstanceId.isEmpty() || !newPrimaryGatewayInstanceId.equals(formerPrimaryGatwayInstanceId.get())) {
            LOGGER.debug("Changing the primary gateway metadata from {} to {}", formerPrimaryGatwayInstanceId, newPrimaryGatewayInstanceId);
            Set<InstanceMetaData> instanceMetaDataSet = instanceMetaDataRepository.findNotTerminatedForStack(stack.getId());
            InstanceMetaData newPrimaryGateway = findInstanceMetaDataByInstanceId(instanceMetaDataSet, newPrimaryGatewayInstanceId);

            formerPrimaryGatwayInstanceId.ifPresent(formerId -> {
                InstanceMetaData formerPrimaryGateway = findInstanceMetaDataByInstanceId(instanceMetaDataSet, formerId);
                formerPrimaryGateway.setInstanceMetadataType(GATEWAY);
                instanceMetaDataRepository.save(formerPrimaryGateway);
                LOGGER.debug("The primary gateway {} metadata has been changed to a regular gateway.", formerId);
            });
            newPrimaryGateway.setInstanceMetadataType(GATEWAY_PRIMARY);
            instanceMetaDataRepository.save(newPrimaryGateway);
            LOGGER.debug("The regular gateway {} metadata has been changed to a primary gateway.", newPrimaryGatewayInstanceId);
        } else {
            LOGGER.debug("The primary gateway {} metadata did not change", newPrimaryGatewayInstanceId);
        }
    }

}