"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.McpPermissionGuard = void 0;
const api_prisma_1 = require("@hed-hog/api-prisma");
const common_1 = require("@nestjs/common");
let McpPermissionGuard = class McpPermissionGuard {
    constructor(prisma) {
        this.prisma = prisma;
    }
    async canActivate(context) {
        var _a, _b;
        const request = context.switchToHttp().getRequest();
        // Only POST requests carry tool invocations
        if (request.method !== 'POST')
            return true;
        const body = request.body;
        const toolName = (body === null || body === void 0 ? void 0 : body.method) === 'tools/call' ? (_a = body === null || body === void 0 ? void 0 : body.params) === null || _a === void 0 ? void 0 : _a.name : undefined;
        // tools/list, initialize, ping, etc. — no per-tool permission check needed
        if (!toolName)
            return true;
        const userId = (_b = request === null || request === void 0 ? void 0 : request.auth) === null || _b === void 0 ? void 0 : _b.sub;
        const count = await this.prisma.route.count({
            where: {
                type: 'MCP',
                tool_name: toolName,
                role_route: {
                    some: {
                        role: {
                            role_user: {
                                some: { user_id: userId },
                            },
                        },
                    },
                },
            },
        });
        if (count === 0) {
            throw new common_1.ForbiddenException(`Access denied to MCP tool '${toolName}'`);
        }
        return true;
    }
};
exports.McpPermissionGuard = McpPermissionGuard;
exports.McpPermissionGuard = McpPermissionGuard = __decorate([
    (0, common_1.Injectable)(),
    __metadata("design:paramtypes", [api_prisma_1.PrismaService])
], McpPermissionGuard);
//# sourceMappingURL=mcp-permission.guard.js.map