import { getSession } from "../lib/neo4j.js";
import { embed } from "../lib/embeddings.js";
import { buildTextRepresentation } from "./memory-write.js";
export async function memoryUpdate(params) {
    const { nodeId, properties, accountId } = params;
    if (Object.keys(properties).length === 0) {
        throw new Error("No properties to update — provide at least one property.");
    }
    // Filter out restricted keys that should not be overwritten by the caller
    const restricted = new Set(["embedding", "accountId", "createdAt", "createdOn"]);
    const safeProps = {};
    for (const [key, value] of Object.entries(properties)) {
        if (!restricted.has(key)) {
            safeProps[key] = value;
        }
    }
    if (Object.keys(safeProps).length === 0) {
        throw new Error("All provided properties are restricted and cannot be updated.");
    }
    const session = getSession();
    try {
        // Match by element ID AND accountId to prevent cross-account edits
        const updateQuery = `
      MATCH (n)
      WHERE elementId(n) = $nodeId AND n.accountId = $accountId
      SET n += $props, n.updatedAt = $updatedAt
      RETURN elementId(n) AS nodeId, labels(n) AS nodeLabels, properties(n) AS allProps
    `;
        const result = await session.run(updateQuery, {
            nodeId,
            accountId,
            updatedAt: new Date().toISOString(),
            props: safeProps,
        });
        if (result.records.length === 0) {
            throw new Error(`Node not found or not owned by this account (ID: ${nodeId}).`);
        }
        const record = result.records[0];
        const updatedNodeId = record.get("nodeId");
        const nodeLabels = record.get("nodeLabels");
        const allProps = record.get("allProps");
        // Re-embed from updated properties
        const propsForEmbed = { ...allProps };
        delete propsForEmbed.embedding;
        delete propsForEmbed.accountId;
        try {
            const textForEmbedding = buildTextRepresentation(nodeLabels, propsForEmbed);
            const embedding = await embed(textForEmbedding);
            await session.run(`MATCH (n) WHERE elementId(n) = $nodeId SET n.embedding = $embedding`, { nodeId: updatedNodeId, embedding });
        }
        catch {
            // Properties were updated successfully — embedding re-computation failed.
            // Stale embedding is acceptable; the node remains searchable with the old vector.
            // memory-reindex can fix this later.
        }
        return { nodeId: updatedNodeId, labels: nodeLabels, updated: true };
    }
    finally {
        await session.close();
    }
}
//# sourceMappingURL=memory-update.js.map