// graphql-publishing/src/cypher/songwriter/agreement/updateAgreementsControlled.cypher
MATCH (sw:PublishingSongWriter {id: $songWriterId})
WITH sw
MATCH (sw)-[oldRel:HAS_AGREEMENT]->(a:PublishingAgreement)
CALL {
    WITH a, oldRel
    SET
        oldRel.lastModifiedAt = datetime(),
        oldRel.lastModifiedBy = $identityId,
        a.lastModifiedAt = datetime(),
        a.lastModifiedBy = $identityId
} IN TRANSACTIONS
WITH sw, a

OPTIONAL MATCH (a)<-[rel:HAS_AGREEMENT]-(:PublishingComposition)
CALL {
    WITH rel
    SET
        rel.lastModifiedAt = datetime(),
        rel.lastModifiedBy = $identityId
} IN TRANSACTIONS
WITH sw, a

OPTIONAL MATCH (a)<-[rel:HAS_AGREEMENT]-(:PublishingPublisher)
CALL {
    WITH rel
    SET
        rel.lastModifiedAt = datetime(),
        rel.lastModifiedBy = $identityId
} IN TRANSACTIONS
WITH sw, a

SET
  a.controlled = $isControlled,
  a.lastModifiedAt = datetime(),
  a.lastModifiedBy = $identityId
WITH sw

MATCH (a2:PublishingAgreement)<-[:HAS_AGREEMENT]-(sw)-[:HAS_AGREEMENT]->(a1:PublishingAgreement)
WHERE
    a1 <> a2
    AND a1.controlled = a2.controlled AND a1.excludedTerritories = a2.excludedTerritories AND
    a1.labelUUID = a2.labelUUID AND a1.pubPublisherID = a2.pubPublisherID AND a1.pubWriterID = a2.pubWriterID
WITH collect(DISTINCT a1) as agreements, sw
CALL apoc.refactor.mergeNodes(agreements, {
    properties: "discard",
    mergeRels: true
})
YIELD node
WITH node as agreement,sw

RETURN agreement
