"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);
};
var __param = (this && this.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.McpSettingsController = void 0;
const backend_common_1 = require("@n8n/backend-common");
const db_1 = require("@n8n/db");
const decorators_1 = require("@n8n/decorators");
const n8n_workflow_1 = require("n8n-workflow");
const update_mcp_settings_dto_1 = require("./dto/update-mcp-settings.dto");
const update_workflow_availability_dto_1 = require("./dto/update-workflow-availability.dto");
const mcp_api_key_service_1 = require("./mcp-api-key.service");
const mcp_settings_service_1 = require("./mcp.settings.service");
const collaboration_service_1 = require("../../collaboration/collaboration.service");
const not_found_error_1 = require("../../errors/response-errors/not-found.error");
const middlewares_1 = require("../../middlewares");
const workflow_finder_service_1 = require("../../workflows/workflow-finder.service");
const workflow_service_1 = require("../../workflows/workflow.service");
let McpSettingsController = class McpSettingsController {
    constructor(mcpSettingsService, logger, moduleRegistry, mcpServerApiKeyService, workflowFinderService, workflowService, collaborationService) {
        this.mcpSettingsService = mcpSettingsService;
        this.logger = logger;
        this.moduleRegistry = moduleRegistry;
        this.mcpServerApiKeyService = mcpServerApiKeyService;
        this.workflowFinderService = workflowFinderService;
        this.workflowService = workflowService;
        this.collaborationService = collaborationService;
    }
    async updateSettings(_req, _res, dto) {
        const enabled = dto.mcpAccessEnabled;
        await this.mcpSettingsService.setEnabled(enabled);
        try {
            await this.moduleRegistry.refreshModuleSettings('mcp');
        }
        catch (error) {
            this.logger.warn('Failed to sync MCP settings to module registry', {
                cause: error instanceof Error ? error.message : String(error),
            });
        }
        return { mcpAccessEnabled: enabled };
    }
    async getApiKeyForMcpServer(req) {
        return await this.mcpServerApiKeyService.getOrCreateApiKey(req.user);
    }
    async rotateApiKeyForMcpServer(req) {
        return await this.mcpServerApiKeyService.rotateMcpServerApiKey(req.user);
    }
    async getMcpEligibleWorkflows(req, res) {
        const options = {
            ...req.listQueryOptions,
            filter: {
                ...req.listQueryOptions?.filter,
                isArchived: false,
                availableInMCP: false,
            },
        };
        const { workflows, count } = await this.workflowService.getMany(req.user, options, false, false, false, ['workflow:update']);
        res.json({ count, data: workflows });
    }
    async toggleWorkflowMCPAccess(req, _res, workflowId, dto) {
        const workflow = await this.workflowFinderService.findWorkflowForUser(workflowId, req.user, ['workflow:update'], { includeActiveVersion: true });
        if (!workflow) {
            this.logger.warn('User attempted to update MCP availability without permissions', {
                workflowId,
                userId: req.user.id,
            });
            throw new not_found_error_1.NotFoundError('Could not load the workflow - you can only access workflows available to you');
        }
        const workflowUpdate = new db_1.WorkflowEntity();
        const currentSettings = workflow.settings ?? {};
        workflowUpdate.settings = {
            ...currentSettings,
            availableInMCP: dto.availableInMCP,
        };
        workflowUpdate.versionId = workflow.versionId;
        const updatedWorkflow = await this.workflowService.update(req.user, workflowUpdate, workflowId);
        const checksum = await (0, n8n_workflow_1.calculateWorkflowChecksum)(updatedWorkflow);
        void this.collaborationService
            .broadcastWorkflowSettingsUpdated(workflowId, { availableInMCP: dto.availableInMCP }, checksum)
            .catch((error) => {
            this.logger.warn('Failed to broadcast workflow settings update', {
                workflowId,
                cause: error instanceof Error ? error.message : String(error),
            });
        });
        return {
            id: updatedWorkflow.id,
            settings: updatedWorkflow.settings,
            versionId: updatedWorkflow.versionId,
        };
    }
};
exports.McpSettingsController = McpSettingsController;
__decorate([
    (0, decorators_1.GlobalScope)('mcp:manage'),
    (0, decorators_1.Patch)('/settings'),
    __param(2, decorators_1.Body),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object, Object, update_mcp_settings_dto_1.UpdateMcpSettingsDto]),
    __metadata("design:returntype", Promise)
], McpSettingsController.prototype, "updateSettings", null);
__decorate([
    (0, decorators_1.GlobalScope)('mcpApiKey:create'),
    (0, decorators_1.Get)('/api-key'),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object]),
    __metadata("design:returntype", Promise)
], McpSettingsController.prototype, "getApiKeyForMcpServer", null);
__decorate([
    (0, decorators_1.GlobalScope)('mcpApiKey:rotate'),
    (0, decorators_1.Post)('/api-key/rotate'),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object]),
    __metadata("design:returntype", Promise)
], McpSettingsController.prototype, "rotateApiKeyForMcpServer", null);
__decorate([
    (0, decorators_1.Get)('/workflows', { middlewares: middlewares_1.listQueryMiddleware }),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object, Object]),
    __metadata("design:returntype", Promise)
], McpSettingsController.prototype, "getMcpEligibleWorkflows", null);
__decorate([
    (0, decorators_1.ProjectScope)('workflow:update'),
    (0, decorators_1.Patch)('/workflows/:workflowId/toggle-access'),
    __param(2, (0, decorators_1.Param)('workflowId')),
    __param(3, decorators_1.Body),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object, Object, String, update_workflow_availability_dto_1.UpdateWorkflowAvailabilityDto]),
    __metadata("design:returntype", Promise)
], McpSettingsController.prototype, "toggleWorkflowMCPAccess", null);
exports.McpSettingsController = McpSettingsController = __decorate([
    (0, decorators_1.RestController)('/mcp'),
    __metadata("design:paramtypes", [mcp_settings_service_1.McpSettingsService,
        backend_common_1.Logger,
        backend_common_1.ModuleRegistry,
        mcp_api_key_service_1.McpServerApiKeyService,
        workflow_finder_service_1.WorkflowFinderService,
        workflow_service_1.WorkflowService,
        collaboration_service_1.CollaborationService])
], McpSettingsController);
//# sourceMappingURL=mcp.settings.controller.js.map