"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.McpAuthGuard = void 0;
const api_prisma_1 = require("@hed-hog/api-prisma");
const common_1 = require("@nestjs/common");
const security_service_1 = require("../../security/security.service");
const token_service_1 = require("../../token/token.service");
let McpAuthGuard = class McpAuthGuard {
    constructor(tokenService, prisma, security) {
        this.tokenService = tokenService;
        this.prisma = prisma;
        this.security = security;
    }
    async canActivate(context) {
        var _a, _b, _c;
        const request = context.switchToHttp().getRequest();
        const locale = (_c = (_b = (_a = request.headers['accept-language']) === null || _a === void 0 ? void 0 : _a.split(',')[0]) === null || _b === void 0 ? void 0 : _b.split('-')[0]) !== null && _c !== void 0 ? _c : 'en';
        const token = this.extractToken(request);
        if (!token) {
            throw new common_1.UnauthorizedException('MCP: Bearer token required');
        }
        if (token.startsWith('hedhog_mcp_')) {
            return this.verifyApiKey(request, token);
        }
        request['auth'] = await this.tokenService.verify(locale, token);
        return true;
    }
    async verifyApiKey(request, token) {
        const hash = this.security.hashWithPepper(token);
        const apiKey = await this.prisma.mcp_api_key.findFirst({
            where: { token_hash: hash, revoked_at: null },
        });
        if (!apiKey) {
            throw new common_1.UnauthorizedException('MCP: Invalid API key');
        }
        if (apiKey.expires_at && apiKey.expires_at <= new Date()) {
            throw new common_1.UnauthorizedException('MCP: API key expired');
        }
        this.prisma.mcp_api_key.update({
            where: { id: apiKey.id },
            data: { last_used_at: new Date() },
        }).catch(() => { });
        request['auth'] = { sub: apiKey.user_id, sessionId: null };
        return true;
    }
    extractToken(request) {
        var _a, _b;
        const [type, token] = (_b = (_a = request.headers.authorization) === null || _a === void 0 ? void 0 : _a.split(' ')) !== null && _b !== void 0 ? _b : [];
        return type === 'Bearer' ? token : undefined;
    }
};
exports.McpAuthGuard = McpAuthGuard;
exports.McpAuthGuard = McpAuthGuard = __decorate([
    (0, common_1.Injectable)(),
    __metadata("design:paramtypes", [token_service_1.TokenService,
        api_prisma_1.PrismaService,
        security_service_1.SecurityService])
], McpAuthGuard);
//# sourceMappingURL=mcp-auth.guard.js.map