import { getSession } from "../lib/neo4j.js";
import { int } from "neo4j-driver";
/**
 * Query workflow execution history.
 * Optionally filter by workflowId and/or status.
 * Returns runs ordered by startedAt DESC with per-step status counts.
 */
export async function workflowRuns(params) {
    const { accountId, workflowId, status, limit = 20 } = params;
    const conditions = ["r.accountId = $accountId"];
    if (workflowId)
        conditions.push("r.workflowId = $workflowId");
    if (status)
        conditions.push("r.status = $status");
    const whereClause = conditions.join(" AND ");
    const query = `
    MATCH (r:WorkflowRun)-[:RUN_OF]->(w:Workflow)
    WHERE ${whereClause}
    OPTIONAL MATCH (r)-[:HAS_RESULT]->(sr:StepResult)
    WITH r, w,
         count(sr) AS stepsTotal,
         count(CASE WHEN sr.status = 'completed' THEN 1 END) AS stepsCompleted,
         count(CASE WHEN sr.status = 'degraded' THEN 1 END) AS stepsDegraded,
         count(CASE WHEN sr.status = 'skipped' THEN 1 END) AS stepsSkipped,
         count(CASE WHEN sr.status = 'failed' THEN 1 END) AS stepsFailed
    RETURN r, w.name AS workflowName, stepsTotal, stepsCompleted, stepsDegraded, stepsSkipped, stepsFailed
    ORDER BY r.startedAt DESC
    LIMIT $limit`;
    const session = getSession();
    try {
        const result = await session.run(query, {
            accountId,
            workflowId,
            status,
            limit: int(limit),
        });
        return result.records.map((rec) => {
            const r = rec.get("r").properties;
            const toNum = (v) => {
                if (typeof v === "object" && v !== null && "toNumber" in v) {
                    return v.toNumber();
                }
                return Number(v);
            };
            return {
                runId: r.runId,
                workflowId: r.workflowId,
                workflowName: rec.get("workflowName"),
                trigger: r.trigger,
                status: r.status,
                startedAt: r.startedAt,
                completedAt: r.completedAt ?? null,
                error: r.error ?? null,
                stepsCompleted: toNum(rec.get("stepsCompleted")),
                stepsDegraded: toNum(rec.get("stepsDegraded")),
                stepsSkipped: toNum(rec.get("stepsSkipped")),
                stepsFailed: toNum(rec.get("stepsFailed")),
                stepsTotal: toNum(rec.get("stepsTotal")),
            };
        });
    }
    finally {
        await session.close();
    }
}
//# sourceMappingURL=workflow-runs.js.map