/**
 * Phase 6 — materialise persistent :BACKLINKS edges (Task 596).
 *
 * For every (src)-[:MENTIONS|REFERENCES]->(tgt) pair scoped to accountId,
 * MERGE (tgt)-[:BACKLINKS]->(src). MERGE is idempotent — re-running
 * produces no duplicate edges and only newly-created edges set createdAt.
 *
 * proposed = total (src,tgt) pairs found in forward direction.
 * applied  = total BACKLINKS edges after the MERGE (new + pre-existing;
 *            Cypher cannot distinguish ON CREATE count from total in a
 *            single MERGE pass without APOC).
 */
export async function phaseBacklinks(ctx) {
    const start = Date.now();
    const { accountId, session } = ctx;
    const result = await session.run(`MATCH (src)-[:MENTIONS|REFERENCES]->(tgt)
     WHERE src.accountId = $accountId AND tgt.accountId = $accountId
     WITH src, tgt
     MERGE (tgt)-[bl:BACKLINKS]->(src)
     ON CREATE SET bl.accountId = $accountId,
                   bl.createdAt = datetime()
     RETURN count(src) AS proposed,
            count(CASE WHEN bl.createdAt IS NOT NULL THEN 1 END) AS applied`, { accountId });
    const proposed = Number(result.records[0]?.get("proposed") ?? 0);
    const applied = Number(result.records[0]?.get("applied") ?? 0);
    const elapsedMs = Date.now() - start;
    process.stderr.write(`[dream-cycle] phase=6 op=backlinks-written accountId=${accountId} count=${applied} elapsedMs=${elapsedMs}\n`);
    return {
        phase: 6,
        name: "backlinks",
        durationSec: Math.round(elapsedMs / 1000),
        proposed,
        applied,
        deferred: 0,
    };
}
//# sourceMappingURL=phase-backlinks.js.map