<?xml version="1.0" encoding="UTF-8"?>
<changelog xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://www.liquigraph.org/schema/1.0/liquigraph.xsd">
    <changeset id="DISTRO-4674-fix_bad_normalized_names:1" author="owright" run-on-change="true">
        <query>
            <![CDATA[
                CALL apoc.trigger.pause('setLabelParticipantNormalizedName');
            ]]>
        </query>
    </changeset>

    <changeset id="DISTRO-4674-fix_bad_normalized_names:2" author="owright" run-on-change="true">
        <query>
            <![CDATA[
                CALL apoc.periodic.iterate(
                    '
                        MATCH (lp:LabelParticipant)
                        WHERE toLower(trim(apoc.text.regreplace(lp.normalizedName, "[ ]+", ""))) <> lp.normalizedName
                        RETURN lp
                    ',
                    '
                        SET lp.normalizedName = toLower(trim(apoc.text.regreplace(lp.name, "[ ]+", "")))
                    ',
                    {
                        batchSize: 1,
                        parallel: false,
                        retries: 0
                    }
                );
                // NOTE: We expect failures here when the nodes have a conflict on normalizedName.
            ]]>
        </query>
    </changeset>

    <changeset id="DISTRO-4674-fix_bad_normalized_names:3" author="owright" run-on-change="true">
        <query>
            <![CDATA[
                CALL apoc.periodic.iterate(
                    '
                        MATCH (lp:LabelParticipant)
                        WHERE toLower(trim(apoc.text.regreplace(lp.normalizedName, "[ ]+", ""))) <> lp.normalizedName
                        RETURN lp
                    ',
                    '
                        SET lp.normalizedName = toLower(trim(apoc.text.regreplace(lp.name, "[ ]+", ""))) + "-" + lp.uuid
                    ',
                    {
                        batchSize: 1000,
                        parallel: false,
                        retries: 1
                    }
                )
                // NOTE: This should no longer have any errors
                YIELD failedOperations, errorMessages, failedBatches, batch
                CALL apoc.util.validate(failedOperations > 0, "At least one sub-operation failed: %s", [reduce(all_errors = "", error IN keys(errorMessages) | all_errors + ", " + error)])
                CALL apoc.util.validate(failedBatches > 0, "At least one batch failed: %s", [reduce(all_errors = "", error IN keys(batch.errors) | all_errors + ", " + error)])
                RETURN 0
            ]]>
        </query>
    </changeset>

    <changeset id="DISTRO-4674-fix_bad_normalized_names:4" author="owright" run-on-change="true">
        <query>
            <![CDATA[
                CALL apoc.trigger.resume('setLabelParticipantNormalizedName');
            ]]>
        </query>
    </changeset>
</changelog>
