import { getSession } from "../lib/neo4j.js";
export async function contactUpdate(params) {
    const { nodeId, email, telephone, updates, accountId } = params;
    if (!nodeId && !email && !telephone) {
        throw new Error("Either nodeId, email, or telephone must be provided");
    }
    const session = getSession();
    try {
        let matchClause;
        const queryParams = { accountId };
        if (nodeId) {
            matchClause = `MATCH (p:Person) WHERE elementId(p) = $nodeId AND p.accountId = $accountId`;
            queryParams.nodeId = nodeId;
        }
        else if (email) {
            matchClause = `MATCH (p:Person {email: $email, accountId: $accountId})`;
            queryParams.email = email.toLowerCase();
        }
        else {
            matchClause = `MATCH (p:Person {telephone: $telephone, accountId: $accountId})`;
            queryParams.telephone = telephone.trim();
        }
        // Build SET clauses from updates (excluding protected fields)
        const protectedFields = new Set(["accountId", "email", "createdOn", "embedding"]);
        const setClauses = [];
        let paramIndex = 0;
        for (const [key, value] of Object.entries(updates)) {
            if (protectedFields.has(key))
                continue;
            const paramName = `val_${paramIndex}`;
            setClauses.push(`p.${key} = $${paramName}`);
            queryParams[paramName] = value;
            paramIndex++;
        }
        if (setClauses.length === 0) {
            throw new Error("No valid fields to update");
        }
        setClauses.push(`p.updatedAt = $updatedAt`);
        queryParams.updatedAt = new Date().toISOString();
        const query = `
      ${matchClause}
      SET ${setClauses.join(", ")}
      RETURN elementId(p) AS nodeId
    `;
        const result = await session.run(query, queryParams);
        if (result.records.length === 0) {
            throw new Error("Contact not found");
        }
        return {
            nodeId: result.records[0].get("nodeId"),
            updated: true,
        };
    }
    finally {
        await session.close();
    }
}
//# sourceMappingURL=contact-update.js.map