<?xml version="1.0" encoding="UTF-8" ?>
<databaseChangeLog
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
    xmlns:neo4j="http://www.liquibase.org/xml/ns/dbchangelog-ext"
    xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-latest.xsd"
>
    <!--
      Heal the shared Profile counter before creating the profile below.
      IncrementId{nodeName:'Profile'} was behind the current max Profile.profileId
      on PROD, so the create was handing out an already-used profileId and hitting
      the (profileType, profileId) node-key constraint. This changeset only moves
      the counter FORWARD (never backward), so a healthy counter that is already
      ahead of max is left untouched. Safe to run in any environment.
    -->
    <changeSet id="TAP_3570_resync_profile_counter:1" author="amerkulov">
        <neo4j:cypher>
            OPTIONAL MATCH (ap:Profile)
            WHERE ap.profileId IS NOT NULL
            WITH coalesce(max(ap.profileId), 0) AS maxId
            MERGE (inc:IncrementId {nodeName: 'Profile'})
                ON CREATE SET inc.id = maxId + 1
                ON MATCH SET inc.id = CASE WHEN inc.id > maxId THEN inc.id ELSE maxId + 1 END
            RETURN inc.id;
        </neo4j:cypher>
    </changeSet>

    <changeSet id="TAP_3570_create_documents_profile:1" author="amerkulov">
        <neo4j:cypher>
            MATCH (i:Identity)
            WHERE i.id = '5d3d6c29-d11a-43d2-9221-ad31a64b68ff'
            MERGE (increment:IncrementId {nodeName: 'Profile'})
                ON CREATE SET increment.id = 2
                ON MATCH SET increment.id = increment.id + 1
            CREATE (p:Profile {
                profileId: (increment.id-1),
                profileType: 'DocumentsProfile',
                profileName: i.name,
                uuid: apoc.create.uuid(),
                roles: ['payee_management'],
                fullCatalogAccess: true,
                brand: 'orchard',
                createdAt: datetime(),
                lastModifiedAt: datetime(),
                createdBy: 'database/TAP_3570_create_documents_profile:1',
                lastModifiedBy: 'database/TAP_3570_create_documents_profile:1'
            })
            MERGE (i)-[:HAS_PROFILE]->(p)
            RETURN i,p;
        </neo4j:cypher>
    </changeSet>
</databaseChangeLog>
