"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.TypeORMWorkflowsStorage = void 0;
const di_1 = require("@n8n/di");
const storage_1 = require("@mastra/core/storage");
const n8n_workflow_1 = require("n8n-workflow");
const instance_ai_workflow_snapshot_repository_1 = require("../repositories/instance-ai-workflow-snapshot.repository");
let TypeORMWorkflowsStorage = class TypeORMWorkflowsStorage extends storage_1.WorkflowsStorage {
    constructor(snapshotRepo) {
        super();
        this.snapshotRepo = snapshotRepo;
    }
    supportsConcurrentUpdates() {
        return false;
    }
    async dangerouslyClearAll() {
        await this.snapshotRepo.clear();
    }
    async persistWorkflowSnapshot(args) {
        const existing = await this.snapshotRepo.findOneBy({
            runId: args.runId,
            workflowName: args.workflowName,
        });
        const snapshot = JSON.stringify(args.snapshot);
        const status = args.snapshot.status ?? null;
        if (existing) {
            await this.snapshotRepo.update({ runId: args.runId, workflowName: args.workflowName }, {
                snapshot,
                status,
                resourceId: args.resourceId ?? null,
            });
        }
        else {
            const entity = this.snapshotRepo.create({
                runId: args.runId,
                workflowName: args.workflowName,
                resourceId: args.resourceId ?? null,
                status,
                snapshot,
            });
            await this.snapshotRepo.save(entity);
        }
    }
    async loadWorkflowSnapshot({ workflowName, runId, }) {
        const entity = await this.snapshotRepo.findOneBy({ runId, workflowName });
        if (!entity)
            return null;
        return (0, n8n_workflow_1.jsonParse)(entity.snapshot);
    }
    async updateWorkflowState({ workflowName, runId, opts, }) {
        const snapshot = await this.loadWorkflowSnapshot({
            workflowName,
            runId,
        });
        if (!snapshot)
            return undefined;
        if (opts.status !== undefined)
            snapshot.status = opts.status;
        if (opts.error !== undefined)
            snapshot.error = opts.error;
        if (opts.suspendedPaths !== undefined) {
            snapshot.suspendedPaths = opts.suspendedPaths;
        }
        if (opts.resumeLabels !== undefined) {
            snapshot.resumeLabels = opts.resumeLabels;
        }
        await this.snapshotRepo.update({ runId, workflowName }, {
            snapshot: JSON.stringify(snapshot),
            status: snapshot.status ?? null,
        });
        return snapshot;
    }
    async updateWorkflowResults({ workflowName, runId, stepId, result, }) {
        const snapshot = await this.loadWorkflowSnapshot({
            workflowName,
            runId,
        });
        if (!snapshot)
            return {};
        snapshot.result ??= {};
        snapshot.result[stepId] = result;
        await this.snapshotRepo.update({ runId, workflowName }, { snapshot: JSON.stringify(snapshot) });
        return snapshot.result;
    }
    async listWorkflowRuns(args) {
        const qb = this.snapshotRepo.createQueryBuilder('s');
        if (args?.workflowName) {
            qb.andWhere('s.workflowName = :name', { name: args.workflowName });
        }
        if (args?.resourceId) {
            qb.andWhere('s.resourceId = :rid', { rid: args.resourceId });
        }
        if (args?.status) {
            qb.andWhere('s.status = :status', { status: args.status });
        }
        if (args?.fromDate) {
            qb.andWhere('s.createdAt >= :fromDate', { fromDate: args.fromDate });
        }
        if (args?.toDate) {
            qb.andWhere('s.createdAt <= :toDate', { toDate: args.toDate });
        }
        qb.orderBy('s.createdAt', 'DESC');
        const total = await qb.getCount();
        if (args?.perPage !== undefined && args?.page !== undefined) {
            const perPage = args.perPage === false ? Number.MAX_SAFE_INTEGER : args.perPage;
            qb.skip(args.page * perPage).take(perPage);
        }
        const entities = await qb.getMany();
        const runs = entities.map((e) => ({
            workflowName: e.workflowName,
            runId: e.runId,
            snapshot: (0, n8n_workflow_1.jsonParse)(e.snapshot),
            createdAt: e.createdAt,
            updatedAt: e.updatedAt,
            resourceId: e.resourceId ?? undefined,
        }));
        return { runs, total };
    }
    async getWorkflowRunById({ runId, workflowName, }) {
        const where = { runId };
        if (workflowName)
            where.workflowName = workflowName;
        const entity = await this.snapshotRepo.findOneBy(where);
        if (!entity)
            return null;
        return {
            workflowName: entity.workflowName,
            runId: entity.runId,
            snapshot: (0, n8n_workflow_1.jsonParse)(entity.snapshot),
            createdAt: entity.createdAt,
            updatedAt: entity.updatedAt,
            resourceId: entity.resourceId ?? undefined,
        };
    }
    async deleteWorkflowRunById({ runId, workflowName, }) {
        await this.snapshotRepo.delete({ runId, workflowName });
    }
    async deleteAllByRunId(runId) {
        await this.snapshotRepo.delete({ runId });
    }
};
exports.TypeORMWorkflowsStorage = TypeORMWorkflowsStorage;
exports.TypeORMWorkflowsStorage = TypeORMWorkflowsStorage = __decorate([
    (0, di_1.Service)(),
    __metadata("design:paramtypes", [instance_ai_workflow_snapshot_repository_1.InstanceAiWorkflowSnapshotRepository])
], TypeORMWorkflowsStorage);
//# sourceMappingURL=typeorm-workflows-storage.js.map