import { getSession } from "../lib/neo4j.js";
const ALLOWED_REL_TYPES = ["AFFECTS", "RAISED_BY", "PART_OF", "BLOCKS"];
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
export async function taskRelate(params) {
    const { taskId, accountId, targetId, targetLabel, relType } = params;
    if (!ALLOWED_REL_TYPES.includes(relType)) {
        throw new Error(`Invalid relationship type: ${relType}. Must be one of: ${ALLOWED_REL_TYPES.join(", ")}`);
    }
    const isTaskTarget = targetLabel === "Task";
    const session = getSession();
    try {
        // Verify the source task exists
        const taskCheck = await session.run(`MATCH (t:Task {taskId: $taskId, accountId: $accountId}) RETURN t`, { taskId, accountId });
        if (taskCheck.records.length === 0) {
            throw new Error(`Task not found: ${taskId}`);
        }
        // Verify the target node exists
        // Task targets: match by taskId property (UUID from task-create)
        // Non-Task targets: match by elementId (from memory-search results)
        let targetCheck;
        if (isTaskTarget) {
            targetCheck = await session.run(`MATCH (target:Task {taskId: $targetId, accountId: $accountId}) RETURN target`, { targetId, accountId });
        }
        else {
            targetCheck = await session.run(`MATCH (target)
         WHERE elementId(target) = $targetId AND $targetLabel IN labels(target)
         RETURN target`, { targetId, targetLabel });
        }
        if (targetCheck.records.length === 0) {
            if (isTaskTarget) {
                const hint = !UUID_RE.test(targetId)
                    ? ` (the value looks like an elementId, not a UUID — use the taskId returned by task-create)`
                    : "";
                throw new Error(`Target task not found with taskId: ${targetId}${hint}`);
            }
            else {
                const hint = UUID_RE.test(targetId)
                    ? ` (the value looks like a UUID — non-Task targets require an elementId from memory-search)`
                    : "";
                throw new Error(`Target ${targetLabel} not found with elementId: ${targetId}${hint}`);
            }
        }
        // Create the relationship (idempotent — MERGE avoids duplicates)
        if (isTaskTarget) {
            await session.run(`MATCH (t:Task {taskId: $taskId, accountId: $accountId})
         MATCH (target:Task {taskId: $targetId, accountId: $accountId})
         MERGE (t)-[:${relType}]->(target)`, { taskId, accountId, targetId });
        }
        else {
            await session.run(`MATCH (t:Task {taskId: $taskId, accountId: $accountId})
         MATCH (target) WHERE elementId(target) = $targetId
         MERGE (t)-[:${relType}]->(target)`, { taskId, accountId, targetId });
        }
    }
    finally {
        await session.close();
    }
}
//# sourceMappingURL=task-relate.js.map