import { getSession } from "../lib/neo4j.js";
import { trashNode } from "../../../../../lib/graph-trash/dist/index.js";
export async function workflowDelete(workflowId, accountId) {
    const session = getSession();
    try {
        const gather = await session.run(`MATCH (w:Workflow {workflowId: $workflowId, accountId: $accountId})
       OPTIONAL MATCH (w)-[:HAS_STEP]->(s:WorkflowStep)
       OPTIONAL MATCH (r:WorkflowRun)-[:RUN_OF]->(w)
       OPTIONAL MATCH (r)-[:HAS_RESULT]->(sr:StepResult)
       RETURN elementId(w) AS wid,
              [x IN collect(DISTINCT s)  WHERE x IS NOT NULL | elementId(x)] AS stepIds,
              [x IN collect(DISTINCT r)  WHERE x IS NOT NULL | elementId(x)] AS runIds,
              [x IN collect(DISTINCT sr) WHERE x IS NOT NULL | elementId(x)] AS resultIds`, { workflowId, accountId });
        if (gather.records.length === 0 || gather.records[0].get("wid") === null) {
            throw new Error(`Workflow not found: ${workflowId}`);
        }
        const wid = gather.records[0].get("wid");
        const stepIds = gather.records[0].get("stepIds");
        const runIds = gather.records[0].get("runIds");
        const resultIds = gather.records[0].get("resultIds");
        const cascadeBy = `workflow-delete:cascade-from-${wid}`;
        let stepResults = 0;
        let runs = 0;
        let steps = 0;
        for (const id of resultIds) {
            const r = await trashNode({ session, accountId, elementId: id, by: cascadeBy });
            if (r.trashed)
                stepResults++;
        }
        for (const id of runIds) {
            const r = await trashNode({ session, accountId, elementId: id, by: cascadeBy });
            if (r.trashed)
                runs++;
        }
        for (const id of stepIds) {
            const r = await trashNode({ session, accountId, elementId: id, by: cascadeBy });
            if (r.trashed)
                steps++;
        }
        const root = await trashNode({
            session,
            accountId,
            elementId: wid,
            by: "workflow-delete",
        });
        return {
            workflowId,
            trashedAt: root.trashedAt,
            alreadyTrashed: root.alreadyTrashed,
            cascade: { steps, runs, stepResults },
        };
    }
    finally {
        await session.close();
    }
}
//# sourceMappingURL=workflow-delete.js.map