"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.WorkflowBuilderSessionRepository = void 0;
const node_crypto_1 = require("node:crypto");
const messages_1 = require("@langchain/core/messages");
const ai_workflow_builder_1 = require("@n8n/ai-workflow-builder");
const di_1 = require("@n8n/di");
const typeorm_1 = require("@n8n/typeorm");
const workflow_builder_session_entity_1 = require("./workflow-builder-session.entity");
let WorkflowBuilderSessionRepository = class WorkflowBuilderSessionRepository extends typeorm_1.Repository {
    constructor(dataSource) {
        super(workflow_builder_session_entity_1.WorkflowBuilderSession, dataSource.manager);
    }
    async getSession(threadId) {
        const { workflowId, userId } = this.parseThreadId(threadId);
        const entity = await this.findOne({ where: { workflowId, userId } });
        if (!entity)
            return null;
        const restoredMessages = (0, messages_1.mapStoredMessagesToChatMessages)(entity.messages);
        const messages = (0, ai_workflow_builder_1.isLangchainMessagesArray)(restoredMessages)
            ? restoredMessages
            : [];
        return {
            messages,
            previousSummary: entity.previousSummary ?? undefined,
            updatedAt: entity.updatedAt,
            activeVersionCardId: entity.activeVersionCardId,
            resumeAfterRestoreMessageId: entity.resumeAfterRestoreMessageId,
        };
    }
    async saveSession(threadId, data) {
        const { workflowId, userId } = this.parseThreadId(threadId);
        const messages = (0, messages_1.mapChatMessagesToStoredMessages)(data.messages);
        const previousSummary = data.previousSummary ?? null;
        const activeVersionCardId = data.activeVersionCardId ?? null;
        const resumeAfterRestoreMessageId = data.resumeAfterRestoreMessageId ?? null;
        await this.createQueryBuilder()
            .insert()
            .into(workflow_builder_session_entity_1.WorkflowBuilderSession)
            .values({
            id: (0, node_crypto_1.randomUUID)(),
            workflowId,
            userId,
            messages,
            previousSummary,
            activeVersionCardId,
            resumeAfterRestoreMessageId,
        })
            .orUpdate(['messages', 'previousSummary', 'activeVersionCardId', 'resumeAfterRestoreMessageId'], ['workflowId', 'userId'])
            .execute();
    }
    async deleteSession(threadId) {
        const { workflowId, userId } = this.parseThreadId(threadId);
        await this.delete({ workflowId, userId });
    }
    parseThreadId(threadId) {
        const match = threadId.match(/^workflow-(.+)-user-(.+)$/);
        if (!match) {
            throw new Error(`Invalid thread ID format: ${threadId}`);
        }
        return { workflowId: match[1], userId: match[2] };
    }
};
exports.WorkflowBuilderSessionRepository = WorkflowBuilderSessionRepository;
exports.WorkflowBuilderSessionRepository = WorkflowBuilderSessionRepository = __decorate([
    (0, di_1.Service)(),
    __metadata("design:paramtypes", [typeorm_1.DataSource])
], WorkflowBuilderSessionRepository);
//# sourceMappingURL=workflow-builder-session.repository.js.map